相关Redis配置:

    1. spring:
    2. redis:
    3. # url: redis://lfy:Lfy123456@r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com:6379
    4. host: r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com
    5. port: 6379
    6. password: lfy:Lfy123456
    7. client-type: jedis
    8. jedis:
    9. pool:
    10. max-active: 10
    11. # lettuce:# 另一个用来连接redis的java框架
    12. # pool:
    13. # max-active: 10
    14. # min-idle: 5

    测试Redis连接:

    @SpringBootTest
    public class Boot05WebAdminApplicationTests {
    
        @Autowired
        StringRedisTemplate redisTemplate;
    
    
        @Autowired
        RedisConnectionFactory redisConnectionFactory;
    
        @Test
        void testRedis(){
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
    
            operations.set("hello","world");
    
            String hello = operations.get("hello");
            System.out.println(hello);
    
            System.out.println(redisConnectionFactory.getClass());
        }
    
    }
    

    Redis Desktop Manager:可视化Redis管理软件。
    URL统计拦截器:

    @Component
    public class RedisUrlCountInterceptor implements HandlerInterceptor {
    
        @Autowired
        StringRedisTemplate redisTemplate;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String uri = request.getRequestURI();
    
            //默认每次访问当前uri就会计数+1
            redisTemplate.opsForValue().increment(uri);
    
            return true;
        }
    }
    

    注册URL统计拦截器:

    @Configuration
    public class AdminWebConfig implements WebMvcConfigurer{
    
        @Autowired
        RedisUrlCountInterceptor redisUrlCountInterceptor;
    
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
    
            registry.addInterceptor(redisUrlCountInterceptor)
                    .addPathPatterns("/**")
                    .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**",
                            "/js/**","/aa/**");
        }
    }
    

    Filter、Interceptor 几乎拥有相同的功能?

    • Filter是Servlet定义的原生组件,它的好处是脱离Spring应用也能使用。
    • Interceptor是Spring定义的接口,可以使用Spring的自动装配等功能。

    调用Redis内的统计数据:

    @Slf4j
    @Controller
    public class IndexController {
    
        @Autowired
        StringRedisTemplate redisTemplate;
    
        @GetMapping("/main.html")
        public String mainPage(HttpSession session,Model model){
    
            log.info("当前方法是:{}","mainPage");
    
            ValueOperations<String, String> opsForValue =
                    redisTemplate.opsForValue();
    
            String s = opsForValue.get("/main.html");
            String s1 = opsForValue.get("/sql");
    
            model.addAttribute("mainCount",s);
            model.addAttribute("sqlCount",s1);
    
            return "main";
        }
    }