Spring Boot中操作使用Redis實(shí)現(xiàn)詳解
1.依賴
maven依賴如下,需要說明的是,spring-boot-starter-data-redis里默認(rèn)是使用lettuce作為redis客戶端的驅(qū)動(dòng),但是lettuce其實(shí)用的比較少,我們常用的還是jedis作為客戶端的驅(qū)動(dòng),所以這里排除掉lettuce,引入jedis:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>2.依賴關(guān)系
spring data redis中依賴的關(guān)系:

這個(gè)依賴關(guān)系想表達(dá)的是,Spring 是通過 RedisConnection操作Redis的,RedisConnection 則對原生的 Jedis 行封裝。要獲取RedisConnection接口對象是通過RedisConnectionFactory 生成的 。
3.配置
配置文件進(jìn)行配置:
# Redis 連接配置
# Redis 連接配置
# 單機(jī) Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 連接池配置
spring.redis.jedis.pool.max-idle=30
spring.redis.jedis.pool.max-total=50
spring.redis.jedis.pool.max-wait=2000ms
代碼進(jìn)行配置:
@Configuration
public class RedisConfig {
private RedisConnectionFactory connectionFactory = null;
@Bean
public RedisConnectionFactory initRedisConnectionFactory(){
if(connectionFactory!=null){
return connectionFactory;
}
JedisPoolConfig poolConfig =new JedisPoolConfig();
//最大空閑數(shù)
poolConfig.setMaxIdle(30);
//最大連接數(shù)
poolConfig.setMaxTotal(50);
//最大等待毫秒數(shù)
poolConfig.setMaxWaitMillis(2000);
//創(chuàng)建Jedis連接工廠
JedisConnectionFactory connectionFactory=new JedisConnectionFactory(poolConfig);
//獲取單機(jī)的redis配置,如果是集群的話用集群配置類
RedisStandaloneConfiguration rscfg=connectionFactory.getStandaloneConfiguration();
connectionFactory.setHostName("127.0.0.1");
connectionFactory.setPort(6379);
return connectionFactory;
}
}4.RedisTemplate
這里要說明的是如果是直接使用RedisConnection來操作redis就需要我們手動(dòng)去找RedisConnectionFactory拿RedisConnection,并且需要每次手動(dòng)關(guān)閉RedisConnection。所以Spring Data Redis里面提供了RedisTemplate來方便操作,其封裝自jedis,屏蔽了資源獲取和釋放的步驟。
使用RedisTemplate的時(shí)候要注意的核心是它的序列化器,RedisTemplate有多種序列化器,不同的序列化器在鍵值寫入、讀出redis的過程中使用的序列化方式會(huì)不同,序列化出來的結(jié)果也會(huì)不同。比如處理字符就需要用字符串專用的序列化器、處理對象需要使用對象專用的序列化器。
目前有的序列化器如下:

StringRedisSerializer:
StringRedisSerializer 是 RedisTemplate 默認(rèn)使用的 Key 和 Value 的序列化器,它將字符串序列化為字節(jié)數(shù)組,使用 UTF-8 編碼。由于 Redis 中 Key 和 Value 都是字符串,因此默認(rèn)的 StringRedisSerializer 序列化器已經(jīng)可以滿足大部分情況的需要。
Jackson2JsonRedisSerializer:
Jackson2JsonRedisSerializer 是一個(gè)基于 Jackson 的 Redis Key 和 Value 的序列化器,它可以將對象序列化為 JSON 格式的字符串,并存儲到 Redis 中。使用 Jackson2JsonRedisSerializer 序列化器需要添加 Jackson 的依賴,可以將對象轉(zhuǎn)換為 JSON 格式的字符串,也可以將 JSON 格式的字符串轉(zhuǎn)換為對象。
JdkSerializationRedisSerializer:
JdkSerializationRedisSerializer 是一種基于 Java 自帶的序列化方式的序列化器,它可以將對象序列化為字節(jié)數(shù)組進(jìn)行存儲。雖然 JdkSerializationRedisSerializer 簡單易用,但是它的效率比較低,序列化后的字節(jié)數(shù)組也比較大,不適合存儲大量的數(shù)據(jù)。
GenericJackson2JsonRedisSerializer:
GenericJackson2JsonRedisSerializer 是一個(gè)支持泛型的 Jackson2JsonRedisSerializer,它可以序列化任意類型的對象,并將對象序列化為 JSON 格式的字符串。它在序列化和反序列化時(shí)都需要指定目標(biāo)類型。
OxmSerializer:
OxmSerializer 是一種基于 Spring 的 O/X 映射框架的序列化器,它支持將對象序列化為 XML 格式的字符串。雖然 OxmSerializer 靈活性較高,但是序列化和反序列化的性能比較低,不適合存儲大量的數(shù)據(jù)。
總之,在選擇序列化器時(shí)需要根據(jù)實(shí)際情況進(jìn)行選擇,根據(jù)數(shù)據(jù)類型和性能要求選擇合適的序列化器。
使用的時(shí)候直接set進(jìn)去即可,set的時(shí)候給了很多生效粒度選擇,是對所有redis類型的數(shù)據(jù)結(jié)構(gòu)都生效,還是對某一類redis的數(shù)據(jù)結(jié)構(gòu)類型生效:

比如我想使用String序列化器,在全局都生效:
@Bean
public RedisTemplate<Object,Object> initRedisTemplate(){
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setDefaultSerializer(new StringRedisSerializer());
return redisTemplate;
}5.基礎(chǔ)操作
以下是使用RedisTemplate操作redis基本數(shù)據(jù)類型的代碼示例:
要注意的是@Bean定義RedisTemplate的時(shí)候泛型要和使用時(shí)的泛型對齊。
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setString(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
public String getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void setHash(String key, String hashKey, Object value) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
hashOps.put(key, hashKey, value);
}
public Object getHash(String key, String hashKey) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
return hashOps.get(key, hashKey);
}
public void setList(String key, Object value) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
listOps.rightPush(key, value);
}
public Object getList(String key, long index) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
return listOps.index(key, index);
}
public void setSet(String key, Object value) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
setOps.add(key, value);
}
public Object getSet(String key) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.members(key);
}
public void setZSet(String key, Object value, double score) {
ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
zsetOps.add(key, value, score);
}
public Object getZSet(String key, long start, long end) {
ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
return zsetOps.range(key, start, end);
}
}6.事務(wù)
以下是使用事務(wù)的代碼示例:
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void transactionalOperation() {
// 開啟 Redis 事務(wù)
redisTemplate.multi();
try {
// 執(zhí)行多個(gè) Redis 命令
redisTemplate.opsForValue().set("key1", "value1");
redisTemplate.opsForValue().set("key2", "value2");
// 提交事務(wù)
redisTemplate.exec();
} catch (Exception e) {
// 回滾事務(wù)
redisTemplate.discard();
}
}到此這篇關(guān)于Spring Boot中操作使用Redis實(shí)現(xiàn)詳解的文章就介紹到這了,更多相關(guān)Spring Boot Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot prototype設(shè)置多例不起作用的解決操作
這篇文章主要介紹了springboot prototype設(shè)置多例不起作用的解決操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
springboot config 攔截器使用方法實(shí)例詳解
本文介紹Spring-Boot中使用攔截器的相關(guān)知識,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2018-05-05
SpringBoot利用切面注解及反射實(shí)現(xiàn)事件監(jiān)聽功能
這篇文章主要介紹了springboot事件監(jiān)聽,通過利用切面、注解、反射實(shí)現(xiàn),接下來將對這幾種方式逐一說明,具有很好的參考價(jià)值,希望對大家有所幫助2022-07-07
Spring Boot 集成Shiro的多realm實(shí)現(xiàn)以及shiro基本入門教程
這篇文章主要介紹了Spring Boot 集成Shiro的多realm實(shí)現(xiàn)以及shiro基本入門,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
springboot-curd基于mybatis項(xiàng)目搭建
這篇文章主要介紹了springboot-curd基于mybatis項(xiàng)目搭建,圍繞相關(guān)資料展開詳細(xì)內(nèi)容,希望對正在學(xué)習(xí)的你有所幫助,需要的小伙伴也可以參考一下2022-01-01

