<!-- 配置starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 配置jedis客户端,默认lettuce -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
spring:
redis:
# url: redis://:123456@127.0.0.1:6379
port: 6379
host: 127.0.0.1
username:
password: 123456
# 客户端类型 lettuce(默认) jedis
client-type: jedis
# jedis连接池配置
jedis:
pool:
max-active: 10
# lettuce连接池配置
lettuce:
pool:
max-active: 10
- 案例:redis记录控制器访问次数
- 配置拦截器,用于记录每次请求的记录
// redis记录控制器访问拦截器
@Component
public class UrlRedisControllerInterceptor implements HandlerInterceptor {
// 注入redis客户端模版
@Autowired
StringRedisTemplate redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取请求路径
String uri = request.getRequestURI();
// 记录访问次数自增
redisTemplate.opsForValue().increment(uri);
// 一律放行
return true;
}
}
// 自定义Spring配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
// 在容器中获取Auth拦截器
@Autowired
AuthInterceptor authInterceptor;
// 在容器中获取Redis记录控制器访问拦截器
@Autowired
UrlRedisControllerInterceptor urlRedisControllerInterceptor;
/**
* 拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Auth拦截器
registry.addInterceptor(authInterceptor)
// 需要拦截路径
.addPathPatterns("/**")
// 排除的拦截路径
.excludePathPatterns("/login", "/favicon.ico", "/image/**", "/js/**", "/css/**");
// redis记录控制器访问拦截器
registry.addInterceptor(urlRedisControllerInterceptor)
// 需要拦截路径
.addPathPatterns("/**")
// 排除的拦截路径
.excludePathPatterns("/login", "/favicon.ico", "/image/**", "/js/**", "/css/**");
}
}
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
void redisTest() {
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
String index_num = operations.get("/index");
// index页面访问次数
System.out.println(index_num);
}