springboot整合redis


在springboot1.x系列中,其中連接redis服務器使用的是jedis,但是到了springboot2.x使用的是Lettuce。
關於jedis跟lettuce的區別:

  • Lettuce 和 Jedis 的定位都是Redis的client,所以他們當然可以直接連接redis server。
  • Jedis在實現上是直接連接的redis server,如果在多線程環境下是非線程安全的,這個時候只有使用連接池,為每個Jedis實例增加物理連接
  • Lettuce的連接是基於Netty的,連接實例(StatefulRedisConnection)可以在多個線程間並發訪問,應為StatefulRedisConnection是線程安全的,所以一個連接實例(StatefulRedisConnection)就可以滿足多線程環境下的並發訪問,當然這個也是可伸縮的設計,一個連接實例不夠的情況也可以按需增加連接實例。

新建一個springboot工程
pom文件為

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>spring-boot-redis</artifactId> <properties> <java.version>1.8</java.version> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- redis依賴commons-pool 這個依賴一定要添加 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.56</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> 

yml 文件

server: port: 8080 spring: redis: cluster: nodes: 192.168.159.129:7001,192.168.159.129:7002,192.168.159.129:7003,192.168.159.129:7004,192.168.159.129:7005,192.168.159.129:7006 host: localhost port: 6379 lettuce: pool: #連接池的最大數據庫連接數。設為0表示無限制,如果是jedis 2.4以后用redis.maxTotal maxActive: 600 #最大空閑數 maxIdle: 200 minIdle: 0 #控制一個pool可分配多少個jedis實例,用來替換上面的redis.maxActive,如果是jedis 2.4以后用該屬性 maxTotal: 1000 #最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。 maxWaitMillis: 5000 password: 

redisConfig類

package com.sl.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @author shuliangzhao * @Title: RedisConfiguration * @ProjectName design-parent * @Description: TODO * @date 2019/7/13 16:55 */ @Configuration public class RedisConfiguration { @Value("${spring.redis.cluster.nodes}") private String nodes; @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private Integer port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.lettuce.pool.maxIdle:}") private Integer maxIdle; @Value("${spring.redis.lettuce.pool.minIdle:}") private Integer minIdle; @Value("${spring.redis.lettuce.pool.maxTotal:}") private Integer maxTotal; @Value("${spring.redis.lettuce.pool.maxWaitMillis:}") private Long maxWaitMillis; @Value("${spring.redis.lettuce.pool.maxActive:}") private Long maxActive; @Bean public LettuceConnectionFactory lettuceConnectionFactory() { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxIdle(maxIdle); poolConfig.setMinIdle(minIdle); poolConfig.setMaxTotal(maxTotal); poolConfig.setMaxWaitMillis(maxWaitMillis); LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder() .poolConfig(poolConfig) .build(); //單機redis RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(); redisConfig.setHostName(StringUtils.isBlank(host) ? "localhost":host.split(":")[0]); redisConfig.setPort(port != null ? 6379: Integer.valueOf(host.split(":")[1])); redisConfig.setPassword(StringUtils.isNotBlank(password) ? password : ""); // 集群redis /*RedisClusterConfiguration redisConfig = new RedisClusterConfiguration(); Set<RedisNode> nodeses = new HashSet<>();*/ return new LettuceConnectionFactory(redisConfig, lettucePoolingClientConfiguration); } @Bean public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); //解決查詢緩存轉換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(om); //redisTemplate.setDefaultSerializer(genericJackson2JsonRedisSerializer); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer); return redisTemplate; } } 

User實體類

package com.sl.entity; /** * @author shuliangzhao * @Title: User * @ProjectName design-parent * @Description: TODO * @date 2019/7/13 17:41 */ public class User { private String name; private String age; private String job; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } } 

controller

package com.sl.controller; import com.alibaba.fastjson.JSONObject; import com.sl.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author shuliangzhao * @Title: RedisController * @ProjectName design-parent * @Description: TODO * @date 2019/7/13 17:40 */ @RestController public class RedisController { @Autowired private RedisTemplate<String,Object> redisTemplate; @RequestMapping("/user/save") public void saveUser() { User user = new User(); user.setName("張三"); user.setAge("18"); user.setJob("程序員"); redisTemplate.opsForValue().set("userZhang", JSONObject.toJSONString(user)); } @RequestMapping("/user/get") public String getUser() { return (String)redisTemplate.opsForValue().get("userZhang"); } } 

啟動類

package com.sl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRedisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRedisApplication.class, args); } } 

spring-data-redis的序列化類有下面這幾個:
1.GenericToStringSerializer: 可以將任何對象泛化為字符串並序列化
2.Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer實際上是一樣的
3.JacksonJsonRedisSerializer: 序列化object對象為json字符串
4.JdkSerializationRedisSerializer: 序列化java對象(被序列化的對象必須實現Serializable接口)
5.StringRedisSerializer: 簡單的字符串序列化
6.GenericToStringSerializer:類似StringRedisSerializer的字符串序列化
7.GenericJackson2JsonRedisSerializer:類似Jackson2JsonRedisSerializer,但使用時構造函數不用特定的類參考以上序列化,自定義序列化類;

StringRedisTemplate默認采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存,StringRedisSerializer。
RedisTemplate默認采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。JdkSerializationRedisSerializer
key和hashKey: 推薦使用 StringRedisSerializer: 簡單的字符串序列化
hashValue: 推薦使用 GenericJackson2JsonRedisSerializer:類似Jackson2JsonRedisSerializer,但使用時構造函數不用特定的類。
源碼在github上面 地址為:https://github.com/FadeHub/spring-boot-learn


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM