准備
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的序列化方式。