redis 分布式计数器
使用redis 的string类型可以实现分布式计数器
****************************
示例:使用计数器统计对某一路径的访问次数
RedisCount
@Component
public class RedisCount {
@Autowired
private StringRedisTemplate redisTemplate;
public void incr(String id){
if(redisTemplate.boundValueOps(id).get()==null){
redisTemplate.boundValueOps(id).set("1");
}else{
redisTemplate.boundValueOps(id).increment();
}
}
public String get(String id){
return redisTemplate.boundValueOps(id).get();
}
}
*********************
拦截器
CustomInterceptor
@Configuration
public class CustomInterceptor implements HandlerInterceptor {
@Autowired
private RedisCount redisCount;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String id=request.getParameter("id");
redisCount.incr(id);
return true;
}
}
*********************
注册拦截器
WebConfig
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private CustomInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor).addPathPatterns("/hello");
}
}
*********************
controller 层
HelloController
@RestController
public class HelloController {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private RedisCount redisCount;
@RequestMapping("/hello")
public String hello(@RequestParam("id") String id){
System.out.println("参数id为:"+id);
return id;
}
@RequestMapping("/get")
public String get(String id){
System.out.println("参数:"+id+"访问次数:"+ redisCount.get(id));
return "参数:"+id+"访问次数:"+ redisCount.get(id);
}
}
********************
使用测试