【SpringBoot】Springboot2.x整合Redis(一)
备注:
springboto整合redis依赖于spring-boot-starter-data-redis这个jar
一,项目环境和依赖
1.POM.xml配置
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2.application.properties文件配置
#=========redis基础配置=========
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000
#=========redis线程池设置=========
# 连接池中的最大空闲连接,默认值也是8。
spring.redis.pool.max-idle=200
#连接池中的最小空闲连接,默认值也是0。
spring.redis.pool.min-idle=200
# 如果赋值为-1,则表示不限制;pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
spring.redis.pool.max-active=2000
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时
spring.redis.pool.max-wait=1000
二.测试代码
@RestController @RequestMapping("/api/v1/redis") public class RdisTestController { @Autowired private StringRedisTemplate redisTpl; //jdbcTemplate @Autowired private RedisClient redis; @GetMapping(value="add") public Object add(){ //redisTpl.opsForValue().set("name", "xdclass2018"); redis.set("username", "xddddddd"); return JsonData.buildSuccess(); } @GetMapping(value="get") public Object get(){ //String value = redisTpl.opsForValue().get("name"); String value = redis.get("username"); return JsonData.buildSuccess(value); } @GetMapping(value="save_user") public Object saveUser(){ User user = new User(1, "abc", "11", new Date()); String userStr = JsonUtils.obj2String(user); //项目名:模块名:id/或者其他相关参数 boolean flag = redis.set("base:user:11", userStr); return JsonData.buildSuccess(flag); } @GetMapping(value="find_user") public Object findUser(){ String userStr = redis.get("base:user:11"); User user = JsonUtils.string2Obj(userStr, User.class); return JsonData.buildSuccess(user); } }
三:代码规范
注意:使用Redis缓存数据时,key的命名规范建议:
项目名:模块名:特殊(标识) 例如 base:user:id
这样做的好处是可以在redis中直观的看到各个模块的缓存数据
例如:使用RDM工具观察到,按以上方式创建的key,会自动创建层级文件夹
代码地址: