【SpringBoot整合Redis测试Redis集群案例】
1、第一步,创建springboot项目,并导入依赖
如图,创建项目遇到的第一个问题就是,当type选择maven,jdk选择1.8时,java部分没办法选择1.8的版本,这怎么办呢?
原因:搜了一下,原来是官网的3.xx版本出来后,不再支持jdk1.8了,最低版本要求是jdk17
解决办法:如果是个人练习的话,jdk可以安装jdk1.8,也可以再安装一个jdk17,跟上主流版本。如果一定要使用的话,那么SpringBoot的Service URL可以使用阿里的版本:
https://start.aliyun.com/
SpringBoot的版本我建议还是用2.xx的版本,因为后面的swagger依赖对springboot的版本有要求,如果要用3.xx版本,那么建议先在网上看看springboot版本和swagger依赖的对应关系。
springboot swagger
版本号 3.xx 3.0.0 http://127.0.0.1:8080/swagger-ui/index.html
我将我的依赖贴出来了,你可以用3.0版本,也可以直接复制我的。版本不同配置可能有出入,但是这也是一种学习,遇到问题解决就是了。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.10</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.awd</groupId> <artifactId>redis-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>redis-demo</name> <description>redis-demo</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--Springboot 与 Redis整合依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- <dependency>--> <!-- <groupId>org.springframework.plugin</groupId>--> <!-- <artifactId>spring-plugin-core</artifactId>--> <!-- <version>2.0.0.RELEASE</version>--> <!-- </dependency>--> <!--jedis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.1</version> </dependency> <!--lettuce--> <!-- <dependency>--> <!-- <groupId>io.lettuce</groupId>--> <!-- <artifactId>lettuce-core</artifactId>--> <!-- <version>6.1.8.RELEASE</version>--> <!-- </dependency>--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2、配置文件
server.port = 8080 spring.application.name=redis-demo # ===================== logging ==================== logging.level.root=info logging.level.com.awd.redisdemo=info logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n logging.file.name=D:/project/mylogs2024/redis-demo.log logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n # ======================== swagger ============================ spring.swagger2.enabled=true spring.mvc.pathmatch.matching-strategy=ant_path_matcher# ================== redis 单机 =================== spring.data.redis.database=0 #云服务或虚拟机,总之,ip地址和端口号对应,单机的redis的ip和端口spring.redis.host=192.168.xxx.xxx spring.redis.port=6379 # redis的启动密码 #spring.redis.password=xxxxx #spring.redis.lettuce.pool.max-active=8 #spring.redis.lettuce.pool.max-wait=-1ms #spring.redis.lettuce.pool.max-idle=8 #spring.redis.lettuce.pool.min-idle=0# ================== redis 集群 ====================== spring.redis.password=abc12345 # 获取失败 最大重定向次数 spring.redis.cluster.max-redirects=3 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 # 这里应该不用加,加了也没事,主要是模拟集群某个主机宕机后,让从机上位,变成主机,集群中,根据虚拟机的测试,应该是上位成功了,变成添加key成功,但是springboot有可能没有重新刷新集群拓扑图,还是之前的,导致一直访问那个宕机的主机结点失败。 spring.redis.lettuce.cluster.refresh.adaptive=true # 定时刷新 spring.redis.lettuce.cluster.refresh.period=2000 # 集群所有的结点配置ip和端口,可以根据构建集群关系的那条语句看 spring.redis.cluster.nodes=192.168.xxx.xxx:xxxx,192.168.xxx.xxx:xxxx,192.168.xxx.xxx:xxxx,192.168.xxx.xxx:xxxx,192.168.xxx.xxx:xxxx,192.168.xxx.xxx:xxxx
3、Swagger配置文件
不必多说,这个直接复制粘贴就行。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${spring.swagger2.enabled}")
private Boolean enabled;
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(enabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.awd.redisdemo"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("springboot 利用swagger2构建api接口文档" + "\t" +
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()))
.description("springboot + redis 整合")
.version("1.0")
.termsOfServiceUrl("https://www.baidu.com/")
.build();
}
}
4、配置Controller层接口
这里遇到了一个问题,使用@Resource注解时,因为是自动引用,导入的包是错误的,缺少的包是:javax.annotation-api
@RestController
@Slf4j
@Api(tags = "订单接口")
public class OrderController {
@Resource
private OrderService orderService;
@Resource
private OldOrderService oldOrderService;
@ApiOperation("新增订单")
@RequestMapping(value = "/order/add",method = RequestMethod.POST)
public void addOrder(){
oldOrderService.addOrder();
}
@ApiOperation("查询订单")
@RequestMapping(value = "/order/{keyId}",method = RequestMethod.GET)
public String getOrderById(@PathVariable Integer keyId){
return oldOrderService.getOrderById(keyId);
}
5、Service层配置
别忘了上面的两个注解
@Service
@Slf4j
public class OrderService {
public static final String ORDER_KEY= "ord:";
@Resource
private StringRedisTemplate stringRedisTemplate;
public void addOrder(){
int keyId = ThreadLocalRandom.current().nextInt(1000)+1;
String serialNo = UUID.randomUUID().toString();
String key = ORDER_KEY + keyId;
String values = "京东订单" + serialNo;
stringRedisTemplate.opsForValue().set(key,values);
log.info("***key:{}",key);
log.info("***value:{}",values);
}
public String getOrderById(Integer keyId){
return stringRedisTemplate.opsForValue().get(ORDER_KEY + keyId);
}
}
6、通过java添加进redis库中的value出现乱码问题
这里我用的是SpringRedisTemplate,点击去会发现,对KEY和VALUE,HashKEY和HASHVALUE做了String序列化,所以不会出现乱码。但是如果换做是RedisTemplate,那么肯定是会乱码的,
SpringRedisTemplate继承了RedisTemplate,并在此基础上加了一些配置,包括初始化了String序列化配置。如果你想使用RedisTemplate,那么可以自己手动加序列化:
@Configuration
public class RedisConfig {
// @Bean
// public RedisTemplate<String , Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
// RedisTemplate<String , Object> redisTemplate = new RedisTemplate<>();
// redisTemplate.setConnectionFactory(redisConnectionFactory);
// // 开启序列化
// redisTemplate.setKeySerializer(new StringRedisSerializer());
// redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
// redisTemplate.afterPropertiesSet();
// return redisTemplate;
// }
@Bean
public RedisTemplate<String , Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
RedisTemplate<String , Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
// 开启序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
7、我顺便做了一下单机的测试,用的jedis和Lettuce
// public static void main(String[] args) {
// Jedis jedis = new Jedis("192.168.xxx.xxx",xxxx);
// jedis.auth("xxxxxxx");
// String k1 = jedis.get("k1");
// System.out.println("k1:"+k1);
// }
public static void main(String[] args) {
// 使用构建器链式编程来builder我们RedisURI
RedisURI uri = RedisURI.builder().withHost("192.168.xxx.xxx")
.withPort(xxxx)
.withAuthentication("default","xxxxxxx")
.build();
// 创建客户端链接
RedisClient redisClient = RedisClient.create(uri);
// 连接客户端
StatefulRedisConnection<String, String> connect = redisClient.connect();
// 创建操作的command
RedisCommands<String, String> commands = connect.sync();
// 执行操作,会报错
// sync.set("k2","v2");
String k1 = commands.get("k1");
System.out.println(k1);
// System.out.println(k2);
// 关闭释放资源
connect.close();
redisClient.shutdown();
}
8、Swagger测试
网址:http://localhost:8080/swagger-ui.html
整个流程大概就是这样子,遇到问题不要着急,看看报错,想一想,再搜一搜,总能找到解决办法的。