SpringBoot集成Redis使用Lettuce詳解
Redis是最常用的KV數(shù)據(jù)庫,Spring 通過模板方式(RedisTemplate)提供了對Redis的數(shù)據(jù)查詢和操作功能。
本文主要介紹基于RedisTemplate + lettuce方式對Redis進行查詢和操作的案例。
一、Redis基礎(chǔ)數(shù)據(jù)類型
首先對redis來說,所有的key(鍵)都是字符串。我們在談基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)時,討論的是存儲值的數(shù)據(jù)類型,主要包括常見的5種數(shù)據(jù)類型,分別是:String、List、Set、Zset、Hash。
結(jié)構(gòu)類型 | 結(jié)構(gòu)存儲的值 | 結(jié)構(gòu)的讀寫能力 |
String字符串 | 可以是字符串、整數(shù)或浮點數(shù) | 對整個字符串或字符串的一部分進行操作;對整數(shù)或浮點數(shù)進行自增或自減操作; |
List列表 | 一個鏈表,鏈表上的每個節(jié)點都包含一個字符串 | 對鏈表的兩端進行push和pop操作,讀取單個或多個元素;根據(jù)值查找或刪除元素; |
Set集合 | 包含字符串的無序集合 | 字符串的集合,包含基礎(chǔ)的方法有看是否存在添加、獲取、刪除;還包含計算交集、并集、差集等 |
Hash散列 | 包含鍵值對的無序散列表 | 包含方法有添加、獲取、刪除單個元素 |
Zset有序集合 | 和散列一樣,用于存儲鍵值對 | 字符串成員與浮點數(shù)分數(shù)之間的有序映射;元素的排列順序由分數(shù)的大小決定;包含方法有添加、獲取、刪除單個元素以及根據(jù)分值范圍或成員來獲取元素 |
二、Redis常用連接池
Jedis:是Redis的Java實現(xiàn)客戶端,提供了比較全面的Redis命令的支持。Redisson:實現(xiàn)了分布式和可擴展的Java數(shù)據(jù)結(jié)構(gòu)。Lettuce:高級Redis客戶端,用于線程安全同步,異步和響應(yīng)使用,支持集群,Sentinel,管道和編碼器。
三、SpringBoot集成Redis案例
1、yml配置常量:
redis:
# 地址
host: 192.168.1.66
# 端口,默認為6379
port: 6379
# 數(shù)據(jù)庫索引
database: 0
# 密碼(如沒有密碼請注釋掉)
password: 123456
# 連接超時時間
timeout: 3000
# 是否開啟ssl
ssl: false
lettuce:
pool:
max-active: 1000 # 連接池最大連接數(shù)(使用負值表示沒有限制)
max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-idle: 10 # 連接池中的最大空閑連接
min-idle: 5 # 連接池中的最小空閑連接2、pom.xml引入依賴:
<!--redis依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.0</version>
</dependency>
<!--連接池依賴-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>3、RedisConfig配置類:
package com.cn.common.conf;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
/**
* redis配置類
*
* @author zq
*/
@Configuration
@EnableCaching
public class RedisConfig {
// 倘若 spring.redis.host 不存在,則會默認為127.0.0.1.
@Value("${spring.redis.host:#{'127.0.0.1'}}")
private String hostName;
@Value("${spring.redis.port:#{6379}}")
private int port;
@Value("${spring.redis.password:#{123456}}")
private String password;
@Value("${spring.redis.timeout:#{3000}}")
private int timeout;
@Value("${spring.redis.lettuce.pool.max-idle:#{16}}")
private int maxIdle;
@Value("${spring.redis.lettuce.pool.min-idle:#{1}}")
private int minIdle;
@Value("${spring.redis.lettuce.pool.max-wait:#{16}}")
private long maxWaitMillis;
@Value("${spring.redis.lettuce.pool.max-active:#{16}}")
private int maxActive;
@Value("${spring.redis.database:#{0}}")
private int databaseId;
@Bean
public LettuceConnectionFactory lettuceConnectionFactory() {
RedisConfiguration redisConfiguration = new RedisStandaloneConfiguration(
hostName, port
);
// 設(shè)置選用的數(shù)據(jù)庫號碼
((RedisStandaloneConfiguration) redisConfiguration).setDatabase(databaseId);
// 設(shè)置 redis 數(shù)據(jù)庫密碼
((RedisStandaloneConfiguration) redisConfiguration).setPassword(password);
// 連接池配置
GenericObjectPoolConfig<Object> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxWaitMillis(maxWaitMillis);
LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder
= LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofMillis(timeout));
LettucePoolingClientConfiguration lettucePoolingClientConfiguration = builder.build();
builder.poolConfig(poolConfig);
// 根據(jù)配置和客戶端配置創(chuàng)建連接
LettuceConnectionFactory factory = new LettuceConnectionFactory(redisConfiguration, lettucePoolingClientConfiguration);
return factory;
}
/**
* springboot2.x 使用LettuceConnectionFactory 代替 RedisConnectionFactory
* application.yml配置基本信息后,springboot2.x RedisAutoConfiguration能夠自動裝配
* LettuceConnectionFactory 和 RedisConnectionFactory 及其 RedisTemplate
*
* @param
* @return
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
LettuceConnectionFactory lettuceConnectionFactory
) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
// 使用 FastJsonRedisSerializer 來序列化和反序列化redis 的 value的值
FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
ParserConfig.getGlobalInstance().addAccept("com.muzz");
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
serializer.setFastJsonConfig(fastJsonConfig);
// key 的 String 序列化采用 StringRedisSerializer
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// value 的值序列化采用 fastJsonRedisSerializer
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.afterPropertiesSet();
System.out.println(redisTemplate.getDefaultSerializer());
return redisTemplate;
}
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
// 使用 FastJsonRedisSerializer 來序列化和反序列化redis 的 value的值
FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
ParserConfig.getGlobalInstance().addAccept("com.muzz");
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
serializer.setFastJsonConfig(fastJsonConfig);
return serializer;
}
}
4、RedisUtil工具類:
package com.cn.util;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @ Description: 基于spring和redis的redisTemplate工具類
* 針對所有的hash 都是以h開頭的方法
* 針對所有的Set 都是以s開頭的方法 不含通用方法
* 針對所有的List 都是以l開頭的方法
* @ Modified By:
*/
@Component
@RequiredArgsConstructor
public class RedisUtils {
private RedisTemplate redisTemplate;
private final StringRedisTemplate stringRedisTemplate;
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
this.redisTemplate = redisTemplate;
}
/**
* 獲取key
* @param patten
* @return
*/
public Set keys(String patten){
return stringRedisTemplate.keys(patten);
}
/**
* 指定緩存失效時間
*
* @param key 鍵
* @param time 時間(秒)
*
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據(jù)key 獲取過期時間
*
* @param key 鍵 不能為null
* @return 時間(秒) 返回0代表為永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判斷key是否存在
*
* @param key 鍵
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除緩存
*
* @param key 可以傳一個值 或多個
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
//============================String=============================
/**
* 普通緩存獲取
*
* @param key 鍵
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通緩存放入
*
* @param key 鍵
* @param value 值
* @return true成功 false失敗
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通緩存放入并設(shè)置時間
*
* @param key 鍵
* @param value 值
* @param time 時間(秒) time要大于0 如果time小于等于0 將設(shè)置無限期
* @return true成功 false 失敗
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 遞增
*
* @param key 鍵
* @param delta 要增加幾(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞增因子必須大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 遞減
*
* @param key 鍵
* @param delta 要減少幾(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("遞減因子必須大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
//================================Map=================================
/**
* HashGet
*
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 獲取hashKey對應(yīng)的所有鍵值
*
* @param key 鍵
* @return 對應(yīng)的多個鍵值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @return true 成功 false 失敗
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并設(shè)置時間
*
* @param key 鍵
* @param map 對應(yīng)多個鍵值
* @param time 時間(秒)
* @return true成功 false失敗
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
*
* @param key 鍵
* @param item 項
* @param value 值
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
*
* @param key 鍵
* @param item 項
* @param value 值
* @param time 時間(秒) 注意:如果已存在的hash表有時間,這里將會替換原有的時間
* @return true 成功 false失敗
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 刪除hash表中的值
*
* @param key 鍵 不能為null
* @param item 項 可以使多個 不能為null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判斷hash表中是否有該項的值
*
* @param key 鍵 不能為null
* @param item 項 不能為null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回
*
* @param key 鍵
* @param item 項
* @param by 要增加幾(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash遞減
*
* @param key 鍵
* @param item 項
* @param by 要減少記(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
//============================set=============================
/**
* 根據(jù)key獲取Set中的所有值
*
* @param key 鍵
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根據(jù)value從一個set中查詢,是否存在
*
* @param key 鍵
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將數(shù)據(jù)放入set緩存
*
* @param key 鍵
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 將set數(shù)據(jù)放入緩存
*
* @param key 鍵
* @param time 時間(秒)
* @param values 值 可以是多個
* @return 成功個數(shù)
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 獲取set緩存的長度
*
* @param key 鍵
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值為value的
*
* @param key 鍵
* @param values 值 可以是多個
* @return 移除的個數(shù)
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================
/**
* 獲取list緩存的內(nèi)容
*
* @param key 鍵
* @param start 開始
* @param end 結(jié)束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 獲取list緩存的長度
*
* @param key 鍵
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通過索引 獲取list中的值
*
* @param key 鍵
* @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數(shù)第二個元素,依次類推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 將list放入緩存
*
* @param key 鍵
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將list放入緩存
*
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將list放入緩存
*
* @param key 鍵
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 將list放入緩存
*
* @param key 鍵
* @param value 值
* @param time 時間(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根據(jù)索引修改list中的某條數(shù)據(jù)
*
* @param key 鍵
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N個值為value
*
* @param key 鍵
* @param count 移除多少個
* @param value 值
* @return 移除的個數(shù)
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Cloud入門教程之Zuul實現(xiàn)API網(wǎng)關(guān)與請求過濾
這篇文章主要給大家介紹了關(guān)于Spring Cloud入門教程之Zuul實現(xiàn)API網(wǎng)關(guān)與請求過濾的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-05-05
SpringBoot自定義FailureAnalyzer詳解
這篇文章主要介紹了SpringBoot自定義FailureAnalyzer詳解,FailureAnalyzer是一種在啟動時攔截?exception?并將其轉(zhuǎn)換為?human-readable?消息的好方法,包含在故障分析中,需要的朋友可以參考下2023-11-11
SpringBoot與Redis的令牌主動失效機制實現(xiàn)
本文詳細介紹了基于SpringBoot和Redis實現(xiàn)令牌主動失效機制,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12

