AI智能
改变未来

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@EnableCachingpublic class GitEggSystemApplication {public static void main(String[] args) {SpringApplication.run(GitEggSystemApplication.class,args);}}

5、在Nacos配置文件中添加redis的相关配置,这里使用单机版redis,其他模式配置请参考官方文档

spring:redis:database: 1host: 127.0.0.1port: 6379password: rootssl: falsetimeout: 2000redisson:config: |singleServerConfig:idleConnectionTimeout: 10000connectTimeout: 10000timeout: 3000retryAttempts: 3retryInterval: 1500password: rootsubscriptionsPerConnection: 5clientName: nulladdress: "redis://127.0.0.1:6379"subscriptionConnectionMinimumIdleSize: 1subscriptionConnectionPoolSize: 50connectionMinimumIdleSize: 32connectionPoolSize: 64database: 0dnsMonitoringInterval: 5000threads: 0nettyThreads: 0codec: !<org.redisson.codec.jsonjacksoncodec> {}"transportMode":"NIO"

6、启动项目,使用swagger进行测试通过以上设置的值和获取的结果可知,我们配置的缓存已生效。

本文源码在https://gitee.com/wmz1930/GitEgg 的chapter-20分支。

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » SpringCloud微服务实战——搭建企业级开发框架(二十):集成Reids缓存