redis整合springboot统计实验
配置yaml
redis:
url: redis://....:6379
默认配置
redis:
host: ....
port: 6379
password: ...
测试redis可用
public void testRedis(){
ValueOperation<String,Strings> operations=redisTemplate.opsForValue();
operations.set("hello","world");
String hello=operations.get("hello");
sout(hello)
}
切换客户端类型
也可以切换成Jedis
redis:
host: ....
port: 6379
password: ...
client-type: jedis
jsdis:
pool:
max-active: 10
监控请求的访问次数
拦截器,前置方法,操作redis,记录当前访问路径。
在AdminWebConfig中
@Autowired
RedisUrlCountInterceptor redisUrlCountInterceptor;
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LoginInterceptor())
.addPathPattern("/**")
.excludePathPattern("/","/css/**","/login");//放行请求
registry.addInterceptor(redisUrlConutInterceptor)
.addPathPatterns("/**")
.excludePathPattern("");
}
区别filter和interceptor
Filter是servlet 脱离spring也能使用
Intercptor spring定义接口,可以使用spring自动装配等功能。
自定义拦截器
RedisUrlCountInterceptor
@Compoment
public class RedisUrlCountInterceptor impletments HandlerInterceptor{
@Autowired
StringRedisTemplate redisTemplate;
public boolean preHandle(HttpRequest request,HttpResponse response){
String url=request.getRequestURI();
redisTemplate.opsForValue().increment(uri);
return true;
}
}
redis用完了需要在阿里云释放。