准备
1、创建SpringBoot项目
2、pom文件中需要有Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3、yml中配置Redis
单机Redis配置:
#Redis 配置
spring:
redis:
host: 192.168.81.130
password: 123456
port: 6379
jedis:
pool:
max-active: 20
max-idle: 8
min-idle: 0
max-wait: 2000 #最大等待时间2s
Redis集群配置:
#Redis 配置
spring:
redis:
jedis:
pool:
max-active: 20
max-idle: 8
min-idle: 0
max-wait: 2000 #最大等待时间2s
cluster: #配置集群
nodes: 192.160.81.130:7001,192.160.81.130:7002,192.160.81.130:7003,192.160.81.130:7004,192.160.81.130:7005,192.160.81.130:7006
Redis自动配置类说明
SpringBoot中所有的自动配置都在starter中的xxxAutoConfiguration
类中,每个我们能在yaml中配置的内容都在xxxProperties
类中有说明。
我们查看Redis的配置类:RedisProperties。它提供了一系列Redis所需的配置。
package org.springframework.boot.autoconfigure.data.redis;
@ConfigurationProperties(
prefix = "spring.redis"
)
public class RedisProperties {
private int database = 0;
private String url;
private String host = "localhost";
private String password;
private int port = 6379;
private boolean ssl;
private Duration timeout;
private String clientName;
private RedisProperties.Sentinel sentinel;
private RedisProperties.Cluster cluster;
private final RedisProperties.Jedis jedis = new RedisProperties.Jedis();
private final RedisProperties.Lettuce lettuce = new RedisProperties.Lettuce();
//...
}
SpringBoot中Redis为我们的自动配置都在RedisAutoConfiguration
类中,它通过RedisTemplate,即Redis的模板进行自动装配。StringRedisTemplate继承自RedisTemplate,它只是将RedisTemplate的泛型<Object, Object>
改为了<String,String>
,我们只能在StringRedisTemplate存储String类型。
package org.springframework.boot.autoconfigure.data.redis;
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
使用
测试配置
@SpringBootTest
class BootRedis02ApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
//keys *
void contextLoads() {
Set<String> keys = stringRedisTemplate.keys("*");
for (String key : keys) {
System.out.println(key);
}
}
}
StringRedisTemplate操作Redis
@SpringBootTest
class ApplicationTests {
@Autowired
private StringRedisTemplate redisTemplate;
@Test
//刷新Redis
void flushdb(){
redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushAll();
connection.flushDb();
return "ok";
}
});
}
@Test
void testNormal(){
redisTemplate.keys("*");//获取所有key
redisTemplate.multi();//开启事务
redisTemplate.exec();//提交事务
redisTemplate.watch("");//监听
redisTemplate.unwatch();//取消监听
redisTemplate.delete("k1");//删除k1
Collection<String> keys=null;
redisTemplate.delete(keys);//删除多个key
redisTemplate.randomKey();//随机一个key
redisTemplate.rename("oldKey","newKey");//重命名key
redisTemplate.discard();//放弃事务
//redisTemplate提供的序列化
redisTemplate.getStringSerializer(); //指redis key序列化方式
redisTemplate.getValueSerializer(); //指值的序列化方式
redisTemplate.getHashKeySerializer();//指hash中Value的key序列化方式
redisTemplate.getHashValueSerializer();//指hash Value的 value序列化方式
}
@Test
void testString(){
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
//System.out.println(redisTemplate.getKeySerializer());
//System.out.println(redisTemplate.getValueSerializer());
//其它方法集
RedisOperations<String, String> operations = opsForValue.getOperations();
// opsForValue.get("");
// opsForValue.set("","");
// opsForValue.setIfPresent("","");
// opsForValue.increment("");
// opsForValue.decrement("");
// opsForValue.set("name","xiaoming");
System.out.println(opsForValue.get("name"));
}
@Test
void testList(){
ListOperations<String, String> opsForList = this.redisTemplate.opsForList();
RedisOperations<String, String> operations = opsForList.getOperations();
opsForList.leftPush("","");
opsForList.leftPushAll("","","","");
opsForList.rightPush("","");
opsForList.rightPushAll("","");
opsForList.leftPop("");
opsForList.rightPop("");
List<String> key = opsForList.range("key", 0, -1);
}
@Test
void testHash(){
HashOperations<String, Object, Object> opsForHash = this.redisTemplate.opsForHash();
opsForHash.put("","hashKey","value");
opsForHash.get("","hashKey");
}
@Test
void testSet(){
SetOperations<String, String> opsForSet = this.redisTemplate.opsForSet();
opsForSet.add("","");
opsForSet.members("");
}
@Test
void testZset(){
ZSetOperations<String, String> opsForZSet = this.redisTemplate.opsForZSet();
opsForZSet.add("key","value",1);
}
//集群操作
@Test
void test(){
ClusterOperations<String, String> clusterOperations = this.redisTemplate.opsForCluster();
//关闭集群的7001端口的主机
opsForCluster.shutdown(new RedisClusterNode("192.168.81.130", 7001));
}
}
RedisTemplate操作Redis
@SpringBootTest
class ApplicationRedisTemplateTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
System.out.println(redisTemplate);
System.out.println(redisTemplate.getKeySerializer());
System.out.println(redisTemplate.getValueSerializer());
}
@Test
void testString(){
//这是设置key的序列化方式,因为RedisTemplate<Object,Object> 如果传String key会被当做object进行序列化
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
ValueOperations opsForValue = redisTemplate.opsForValue();
//opsForValue.set("user:1".toString(),new User(1,"xiaoming","wh",new Date()));
User user = (User) opsForValue.get("user:1");
System.out.println(user);
}
@Test
void testString2(){
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
this.redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
ValueOperations opsForValue = redisTemplate.opsForValue();
//opsForValue.set("user:2".toString(),new User(1,"xiaoming","wh",new Date()));
// 若该对象的强转转换,则redis 内部会使用JackSon的工具将字符串->java 对象 ,那jackson 转换为对象时,需要一个对象的类型 ,其实它已经自动获取对象的类型了
User user = (User) opsForValue.get("user:2");
System.out.println(user);
}
}
Redis中的序列化
Redis的序列化规则在package org.springframework.data.redis.serializer
包下的RedisSerializer
接口中。
public interface RedisSerializer<T> {}
若不设置序列化规则,它将使用JDK自动的序列化将对象转换为字节,存到Redis 里面。它可以存在对象到redis里面,如果对象没有序列化,那么默认使用的JDK的序列化方式。