在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文件为
4.0.0
spring-boot-redis
1.8
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
org.springframework.boot
spring-boot-starter-web
2.1.6.RELEASE
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
org.apache.commons
commons-lang3
3.8.1
com.alibaba
fastjson
1.2.56
org.springframework.boot
spring-boot-maven-plugin
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 nodeses = new HashSet<>();*/
return new LettuceConnectionFactory(redisConfig, lettucePoolingClientConfiguration);
}
@Bean
public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate 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 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