这章我们来介绍在系统中引入redisson-spring-boot-starter依赖来实现redis缓存管理
1、在GitEgg-Platform中新建gitegg-platform-redis用于管理工程中用到的Redis公共及通用方法。
<!-- redisson Redis客户端-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>
2、在gitegg-platform-bom的pom.xml文件中添加gitegg-platform-redis
<!-- gitegg cache自定义扩展 -->
<dependency>
<groupId>com.gitegg.platform</groupId>
<artifactId>gitegg-platform-redis</artifactId>
<version>${gitegg.project.version}</version>
</dependency>
3、GitEgg-Platform重新install,在GitEgg-Cloud子工程gitegg-service-system代码SystemController.java中添加设置和获取缓存的测试方法
private final RedissonClient redisson;
private final RedisTemplate<String, String> template;
@ApiOperation(value = "缓存测试设置值")
@GetMapping(value = "redis/set")
public Result redisSet(@RequestParam("id") String id) {
RMap<String, String> m = redisson.getMap("test", StringCodec.INSTANCE);
m.put("1", id);
return Result.success("设置成功");
}
@ApiOperation(value = "缓存测试获取值")
@GetMapping(value = "redis/get")
public Result redisGet() {
BoundHashOperations<String, String, String> hash = template.boundHashOps("test");
String t = hash.get("1");
return Result.success(t);
}
4、gitegg-service-system中的GitEggSystemApplication.java添加@EnableCaching注解
package com.gitegg.service.system;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
/**
* gitegg-system 启动类
*/
@EnableDiscoveryClient
@ComponentScan(basePackages = "com.gitegg")
@MapperScan("com.gitegg.*.*.mapper")
@SpringBootApplication
@EnableCaching
public class GitEggSystemApplication {
public static void main(String[] args) {
SpringApplication.run(GitEggSystemApplication.class,args);
}
}
5、在Nacos配置文件中添加redis的相关配置,这里使用单机版redis,其他模式配置请参考官方文档
spring:
redis:
database: 1
host: 127.0.0.1
port: 6379
password: root
ssl: false
timeout: 2000
redisson:
config: |
singleServerConfig:
idleConnectionTimeout: 10000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
password: root
subscriptionsPerConnection: 5
clientName: null
address: "redis://127.0.0.1:6379"
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 32
connectionPoolSize: 64
database: 0
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
"transportMode":"NIO"
6、启动项目,使用swagger进行测试
image.png
image.png
通过以上设置的值和获取的结果可知,我们配置的缓存已生效。
本章源码在https://gitee.com/wmz1930/gitegg-cloud 和 https://gitee.com/wmz1930/gitegg-platform 的chapter-20分支。
网友评论