SpringCloud微服务实战——搭建企业级开发框架(二十):集成Reids缓存
我们在这里介绍如何在系统中引入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进行测试
通过以上设置的值和获取的结果可知,我们配置的缓存已生效。
本文源码在https://gitee.com/wmz1930/GitEgg 的chapter-20分支。