1,Spring 是如何集成Redis的?
首先我們要使用jar包
<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>
2,我們使用的時候需要用到高級封裝
2,配置Redis
# Redis服務器地址
spring.redis.host=10.1.30.222
# Redis數(shù)據(jù)庫索引(默認為0)
spring.redis.database=0
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
#spring.redis.password=
## 連接超時時間(毫秒)
spring.redis.timeout=30000
# 連接池最大連接數(shù)(使用負值表示沒有限制) 默認 8
spring.redis.lettuce.pool.max-active=8
# 連接池中的最大空閑連接 默認 8
spring.redis.lettuce.pool.max-idle=8
# 連接池中的最小空閑連接 默認 0
spring.redis.lettuce.pool.min-idle=1
#連接池中最大空閑等待時間,3s沒有活干的時候直接驅逐該鏈接
spring.redis.lettuce.pool.min-evictable-idle-time-millis = 3000
# 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
spring.redis.lettuce.pool.max-wait=-1
StringRedisTemplate
String
public class StringDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String key = "zhengzhou";
public void test() {
stringRedisTemplate.opsForValue().set(key, "我的家鄉(xiāng)", 30, TimeUnit.SECONDS);
String value = stringRedisTemplate.opsForValue().get(key);
System.out.println(value);
}
}
Java
Hash
@Component
public class HashDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String key ="zhouxingxing";
public void test(){
stringRedisTemplate.opsForHash().put(key,"20220325","鄭州");
stringRedisTemplate.opsForHash().put(key,"20220326","洛陽");
List<Object> values = stringRedisTemplate.opsForHash().values(key);
for (Object value:values){
System.out.println(value);
}
}
}
Java
List
@Component
public class ListDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String key ="onewayroad";
void test(){
stringRedisTemplate.opsForList().leftPush(key,"周星星");
stringRedisTemplate.opsForList().leftPush(key,"張敏");
stringRedisTemplate.opsForList().leftPush(key,"李大錘");
String value = stringRedisTemplate.opsForList().rightPop(key);
System.out.println(value);
}
}
@Test
void test6() {
// 如果一些原生命令,spring 沒有給我們封裝,redisTemplate.execute(new RedisCallback)
while (true){
System.out.println("開始一輪監(jiān)聽");
List<byte[]> rawResults = redisTemplateProduct.execute(new RedisCallback<List<byte[]>>() {
@Override
public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
return connection.bRPop(5,"product.hot".getBytes());
}
});
if(ObjUtil.isNotEmpty(rawResults)){
byte[] rawKey = rawResults.get(0);
byte[] rawValue = rawResults.get(1);
Product product = (Product)redisTemplateProduct.getValueSerializer().deserialize(rawValue);
System.out.println(product);
}
}
Java
Set
@Component
public class SetDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String zhouxingxing ="zhouxingxing";
private final String zhangmin = "zhangming";
public void test(){
//添加周星星同學感興趣的科目
stringRedisTemplate.opsForSet().add(zhouxingxing,"語文");
stringRedisTemplate.opsForSet().add(zhouxingxing,"數(shù)學");
stringRedisTemplate.opsForSet().add(zhouxingxing,"數(shù)學");
//添加張敏同學感興趣的科目
stringRedisTemplate.opsForSet().add(zhangmin,"數(shù)學");
stringRedisTemplate.opsForSet().add(zhangmin,"英語");
//獲取兩位同學共同感興趣的科目
Set<String> values = stringRedisTemplate.opsForSet().intersect(zhouxingxing, zhangmin);
System.out.println("周星星和張敏共同感興趣的科目為:");
for(String value : values){
System.out.println(value);
}
}
}
Java
ZSet
@Component
public class ZSetDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String key ="zhouxingxing";
public void test(){
//添加周星星同學成績
stringRedisTemplate.opsForZSet().add(key,"語文",98);
stringRedisTemplate.opsForZSet().add(key,"數(shù)學",87);
stringRedisTemplate.opsForZSet().add(key,"英語",75);
//獲取分數(shù)最高的成績
ZSetOperations.TypedTuple<String> values = stringRedisTemplate.opsForZSet().popMax(key);
//打印值
System.out.println("周星星最好成績科目是:"+values.getValue());
System.out.println("周星星最好成績:"+values.getScore());
}
}
Java
BitMap
@Component
public class BitMapDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String key ="sign#2022#zhouxingxing";
public void test(){
//設置簽到
stringRedisTemplate.opsForValue().setBit(key,2,true);
stringRedisTemplate.opsForValue().setBit(key,85,true);
//獲取周星星同學的簽到天數(shù)
RedisCallback<Long> callback = connection -> { return connection.bitCount(key.getBytes(),0,365);};
Long count = stringRedisTemplate.execute(callback);
//打印周星星2022年簽到天數(shù)
System.out.println("周星星2022年一共簽到天數(shù):"+count);
}
}
Java
3.RedisTemplate
3.1泛型約束的使用
@Component
public class RedisTemplateDemo {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, String> redisTemplate_string_string;
@Resource
private RedisTemplate<String, User> redisTemplate;
@Resource(name="redisTemplate")
private ValueOperations<String,User> valueOperations;
private final String key = "useris#01";
public void test() {
User user = User.builder().id(1).name("李四").build();
redisTemplate.opsForValue().set(key,user );
User value = redisTemplate.opsForValue().get(key);
valueOperations.set(key,user );
User value2 = valueOperations.get(key);
System.out.println(value);
}
}
4,亂碼的問題
JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
byte[] serialize = serializer.serialize("user#01");
System.out.println(new String(serialize));
自定義序列化工具
@Configuration
public class RedisConfig {
@Bean //主動注冊了一個名字叫redisTemplate 的bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
// 啟用默認類型推理,將類型信息作為屬性寫入JSON
// 就是把對象的全類名寫入json
mapper.activateDefaultTyping( mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
jackson.setObjectMapper(mapper);
template.setKeySerializer(StringRedisSerializer.UTF_8);
template.setValueSerializer(jackson);
template.setHashKeySerializer(StringRedisSerializer.UTF_8);
template.setHashValueSerializer(jackson);
return template;
}
}
為什么要自定話應該序列化工具,因為他自己提供的不是很好,所以我們要自己定義一個,這樣的話可以把java對象轉化成json和字節(jié)碼存入Redis 里,反序列化就是把json和字節(jié)碼轉化為java對象,泛型指定為?
Object.class
?表示可以處理任何類型的對象。最后返回配置好的?
RedisTemplate
?實例,這樣在整個Spring Boot應用中,當需要使用RedisTemplate進行操作時,將自動使用這個經過JSON序列化配置的模板。
詳細的介紹:
-
@Configuration
?注解表明這是一個配置類,Spring IoC容器將會讀取該類中的bean定義。 -
@Bean
?注解的方法表示該方法會返回一個對象,該對象會被注冊為Spring容器中的bean。在這個例子中,方法名為?redisTemplate
,所以生成的bean的名字也是 "redisTemplate"。 -
方法體中首先創(chuàng)建了一個?
RedisTemplate<Object, Object>
?實例,并將其連接工廠設置為傳入的?RedisConnectionFactory
,這是連接Redis的基礎配置。 -
創(chuàng)建了?
Jackson2JsonRedisSerializer
?實例,用于將Java對象序列化為JSON字符串,反序列化時則將JSON字符串轉回為Java對象。泛型指定為?Object.class
?表示可以處理任何類型的對象。 -
初始化?
ObjectMapper
,它是Jackson庫中用于處理JSON的核心類。這里啟用了默認類型推理(activateDefaultTyping
),這樣在序列化時,即使目標類沒有顯式地聲明類型信息,也能根據(jù)實際運行時類型推斷并在JSON中包含類型信息,這對于處理多態(tài)類型的場景非常有用。 -
將初始化好的?
ObjectMapper
?設置給?Jackson2JsonRedisSerializer
。 -
配置RedisTemplate的序列化策略:文章來源:http://www.zghlxwxcb.cn/news/detail-844226.html
-
template.setKeySerializer(StringRedisSerializer.UTF_8);
?設置鍵(key)的序列化器為?StringRedisSerializer
,以UTF-8格式進行字符串序列化。 -
template.setValueSerializer(jackson);
?設置值(value)的序列化器為剛才創(chuàng)建的?Jackson2JsonRedisSerializer
,即所有值都將轉化為JSON字符串存儲。 -
template.setHashKeySerializer(StringRedisSerializer.UTF_8);
?設置哈希表鍵(hash key)的序列化器也為?StringRedisSerializer
,同樣以UTF-8格式進行字符串序列化。 -
template.setHashValueSerializer(jackson);
?設置哈希表值(hash value)的序列化器為?Jackson2JsonRedisSerializer
,意味著哈希表中的每個值也將被轉化為JSON字符串存儲。
-
最后,返回配置好的?RedisTemplate
?實例,這樣在整個Spring Boot應用中,當需要使用RedisTemplate進行操作時,將自動使用這個經過JSON序列化配置的模板。文章來源地址http://www.zghlxwxcb.cn/news/detail-844226.html
到了這里,關于Spring Boot 使用 Redis的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!