文章目錄
- 總體概述
- 本地Java連接Redis常見問題
- 集成Jedis
- 集成lettuce
- 集成RedisTemplate——推薦使用
- 連接單機
- 連接集群

總體概述
- jedis-lettuce-RedisTemplate三者的聯系
- jedis第一代
- lettuce承上啟下
- redistemplate著重使用
本地Java連接Redis常見問題
- bind配置請注釋掉
- 保護模式設置為no
- Linux系統的防火墻設置
- Redis服務器的IP地址和密碼是否正確
- 忘記寫訪問redis的服務端口號和auth密碼
集成Jedis
- 是什么:Jedis Client是Redis官網推薦的一個面向Java客戶端,庫文件實現了對各類API進行封裝調用
- 步驟
- 建Module
- 改POM.xml
- 寫application.yaml
- 主啟動
- 業務類
<?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.7.11</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.luojia</groupId><artifactId>redis7_study</artifactId><version>0.0.1-SNAPSHOT</version><name>redis7_study</name><description>Demo project for Spring Boot</description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><junit.version>4.12</junit.version><log4j.version>1.2.17</log4j.version><lombok.version>1.16.18</lombok.version></properties><dependencies><!--SpringBoot 通用依賴模塊--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- jedis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>4.3.1</version></dependency><!-- 通用基礎配置 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
server.port=7777
spring.application.name=redis7_study
集成lettuce
-
是什么:Lettuce是一個Redis的Java驅動包,Lettuce翻譯為生菜,就是吃的那種生菜
-
lettuce VS Jedis
-
改POM
-
業務類
集成RedisTemplate——推薦使用
連接單機
- boot整合Redis基礎演示
- 建module:redis7_study
- 改pom
<!-- SpringBoot 與Redis整合依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></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>
- 寫YML
server.port=7777spring.application.name=redis7_study# ===========================logging===========================
logging.level.root=info
logging.1evel.com.luojia.redis7_study.redis7=info
1ogging.pattern.console=%d{yyyy-MM-dd HH:m:ss.SSS} [%thread] %-5level %1ogger- %msg%n1ogging.file.name=F:\workspace\數據結構和算法\Learning-in-practice\Redis\redis7-study
1ogging.pattern.fi1e=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n# ===========================swagge===========================
spring.swagger2.enabled=true
#在springboot2.6.X結合swagger2.9.X會提示documentationPluginsBootstrapper空指針異常,
#原因是在springboot2.6.X中將SpringMVC默認路徑匹配策略MAntPathMatcher更改為athPatternParser,
#導致出錯,解決辦法是matching-strategy 切換回之前ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher# ===========================redis單機===========================
spring.redis.database=0
#修改為自己真實IP
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.lettuce.pool.max-active=8
spring.redis.1ettuce.pool.max-wait=-1ms
spring.redis.1ettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
- 主啟動
- 業務類-配置類
// RedisConfig
package com.luojia.redis7_study.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {/*** *redis序列化的工具定置類,下面這個請一定開啟配置* *127.0.0.1:6379> keys ** *1) “ord:102” 序列化過* *2)“\xaclxedlxeelx05tixeelaord:102” 野生,沒有序列化過* *this.redisTemplate.opsForValue(); //提供了操作string類型的所有方法* *this.redisTemplate.opsForList();// 提供了操作List類型的所有方法* *this.redisTemplate.opsForset(); //提供了操作set類型的所有方法* *this.redisTemplate.opsForHash(); //提供了操作hash類型的所有方認* *this.redisTemplate.opsForZSet(); //提供了操作zset類型的所有方法* param LettuceConnectionFactory* return*/@Beanpublic RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(lettuceConnectionFactory);// 設置key序列化方式stringredisTemplate.setKeySerializer(new StringRedisSerializer());// 設置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替換默認序列化redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}
}
// SwaggerConfig
package com.luojia.redis7_study.config;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.time.LocalDate;
import java.time.format.DateTimeFormatter;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Value("${spring.swagger2.enabled}")private Boolean enabled;@Beanpublic Docket createRestApi() {return new Docket (DocumentationType.SWAGGER_2).apiInfo(apiInfo()).enable(enabled).select().apis(RequestHandlerSelectors.basePackage("com.luojia.redis7_study.config")) //你自己的package.paths (PathSelectors.any()).build();}public ApiInfo apiInfo() {return new ApiInfoBuilder().title("springboot利用swagger2構建api接口文檔 "+"\t"+ DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDate.now())).description( "springboot+redis整合" ).version("1.0").termsOfServiceUrl("https://github.com/Romantic-Lei").build();}}
- 業務類-service
package com.luojia.redis7_study.service;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;@Service
@Slf4j
public class OrderService {@Autowiredprivate RedisTemplate redisTemplate;public static final String ORDER_KEY="ord:";public void addOrder() {int keyId = ThreadLocalRandom.current().nextInt(1000) + 1;String serialNo = UUID.randomUUID().toString();String key = ORDER_KEY+keyId;String value = "JD" + serialNo;redisTemplate.opsForValue().set(key, value);log.info("***key:{}", key);log.info("***value:{}", value);}public String getOrderById(Integer keyId) {return (String)redisTemplate.opsForValue().get(ORDER_KEY+keyId);}
}
- 業務類-controller
package com.luojia.redis7_study.controller;import com.luojia.redis7_study.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@Slf4j
@Api(tags="訂單接口")
public class OrderController {@Autowiredprivate OrderService orderService;@ApiOperation("新增訂單")@PostMapping("/order/add")public void addOrder() {orderService.addOrder();}@ApiOperation("根據keyId查詢訂單")@GetMapping("/order/query")public String queryOrder(Integer keyId) {return orderService.getOrderById(keyId);}}
- 測試
- 項目啟動,連接swagger:http://localhost:7777/swagger-ui.html
- 序列化問題
- 為什么會這樣?RedisTemplate使用的是JDK序列化方式(默認)惹的禍
連接集群
- 啟動Redis集群6臺實例
- 第一次改寫YML
# ===========================redis集群===========================
spring.redis.password=111111
# 獲取失敗 最大重定向次數
spring.redis.cluster.max-redirects=3
spring.redis.lettuce.pool.max-active=8
spring.redis.1ettuce.pool.max-wait=-1ms
spring.redis.1ettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.cluster.nodes=192.168.111.175:6381,192.168.111.175:6382,192.168.111.176:6383,192.168.111.176:6384
- 直接通過微服務訪問Redis集群:一切正常 (http://localhost:7777/swagger-ui.html)
- 問題來了:
- 人為模擬,master-6381機器意外宕機,手動shutdown
- 先對redis集群用命令的方式,手動驗證各種讀寫命令,看看6384是否上位
- Redis Cluster集群能自動感知并自動完成主備切換,對應的slave6384會被選舉為新的master節點
- 通過redis客戶端連接6384可以正常進行讀寫操作
- 微服務客戶端再次讀寫訪問試試
-
故障現象
- SpringBoot客戶端沒有動態感知RedisCluster的最新集群信息
- 經典故障-故障演練:Redis Cluster集群部署采用了3主3從拓撲結構,數據讀寫訪問master節點,slave節點負責備份。當master宕機主從切換成功,redis手動OK,but 2個經典故障
-
導致原因:SpringBoot 2.X版本,Redis默認的連接池采用Lettuce,當Redis集群節點發生變化后,Letture默認是不會刷新節點拓撲
-
解決方案
- 排除lettuce采用Jedis(不推薦)
- 修改源碼,重寫連接工廠實例(極度不推薦)
- 刷新節點集群拓撲動態感應
- 解決方法:
- 調用 RedisClusterClient.reloadPartitions
- 后臺基于時間間隔的周期刷新
- 后臺基于持續的斷開和移動、重定向的自適應更新
- 解決方法:
- 排除lettuce采用Jedis(不推薦)
-
第二次改寫YML
-