Redis操作和统计小实验

测试Redis连接:

application.yaml

redis:
    host: r-bp1hbgff9s71uo6skupd.redis.rds.aliyuncs.com
    port: 6379
    password: qwl:Qin123456

BootWebAdminApplicationTests

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

在这里插入图片描述

切换至jedis

		<!-- 导入jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

URL统计拦截器:

RedisUrlCountInterceptor

@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统计拦截器:

AdminWebConfig

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
    
    
    /**
     * Filter、Interceptor 几乎拥有相同的功能?
     * Filter是Servlet定义的原生组件,它的好处是脱离Spring应用也能使用。
     * Interceptor是Spring定义的接口,可以使用Spring的自动装配等功能。
     */
    @Autowired
    RedisUrlCountInterceptor redisUrlCountInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")  //所有请求都被拦截包括静态资源
                .excludePathPatterns("/", "/login", "/css/**", "/fonts/**",
                        "/images/**", "/js/**"); //放行的请求

        registry.addInterceptor(redisUrlCountInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/", "/login", "/css/**", "/fonts/**",
                        "/images/**", "/js/**"); //放行的请求

    }
}

调用Redis内的统计数据:

IndexController

	@Autowired
    StringRedisTemplate redisTemplate;
    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model){
    
    
    
        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";
    }
	<div class="col-xs-8">
     	 <span class="state-title">  /main.html  </span>
     	 <h4 th:text="${mainCount}">5980</h4>
	</div>
	<div class="col-xs-8">
		<span class="state-title">/sql</span>
		<h4 th:text="${sqlCount}">10,000</h4>
	</div>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_51600120/article/details/114931397
今日推荐