一、版本信息
- JDK 21
- SpringBoot 3.3.0
- Maven 3.9.6
二、pom.xml引入依賴(lài)
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.0</version><!-- 2.7.4↑-->
<relativePath/>
</parent>
<properties>
...
<!--
Web啟動(dòng)器
注意:
1)由于 spring-boot-starter-web 默認(rèn)替我們引入了核心啟動(dòng)器 spring-boot-starter,因此,當(dāng) Spring Boot 項(xiàng)目中的 pom.xml 引入了 spring-boot-starter-web 的依賴(lài)后,就無(wú)須在引入 spring-boot-starter 核心啟動(dòng)器的依賴(lài)了。
2)spring-boot-starter-web 默認(rèn)使用嵌入式的tomcat作為web容器對(duì)外提供HTTP服務(wù)。
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 整合redis的啟動(dòng)器:https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
...
</properties>
三、yml配置
spring:
data:
redis:
## 單擊模式配置
# Redis服務(wù)器地址
host: 127.0.0.1
# Redis服務(wù)器端口號(hào)
port: 6379
# 使用的數(shù)據(jù)庫(kù)索引,默認(rèn)是0
database: 0
# 設(shè)置密碼,如果無(wú)密碼,需注釋該行
password: 123456
# 連接超時(shí)時(shí)間(毫秒)
connect-timeout: 1000
# 操作超時(shí)時(shí)間(毫秒)
timeout: 1000
# 客戶(hù)端名稱(chēng)(不知道干嘛用的)
client-name:
# 驅(qū)動(dòng)類(lèi)型
client-type: lettuce
# 連接池配置
lettuce:
pool:
# 最小空閑連接(默認(rèn)0)
min-idle: 1
# 最大空閑連接(默認(rèn)8)
max-idle: 8
# 最大連接數(shù)(默認(rèn)8,使用負(fù)值表示沒(méi)有限制)
max-active: 16
# 最大阻塞等待時(shí)間,單位毫秒(默認(rèn)-1,負(fù)數(shù)表示沒(méi)限制,永不超時(shí))
max-wait: 2000
ssl:
enabled: false
四、RedisConfig配置類(lèi)
package cn.keyidea.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置類(lèi)
*
* @author qyd
* @date 2024-05-21
**/
@Configuration
public class RedisConfig {
private final static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
/**
* redisTemplate相關(guān)配置
* [@Role(BeanDefinition.ROLE_INFRASTRUCTURE)] 表明這個(gè)bean是完全后臺(tái)模式,不需要被代理。
*
* @param factory Redis連接工廠類(lèi)
* @return 返回配置項(xiàng)對(duì)象
*/
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置連接工廠
template.setConnectionFactory(factory);
ObjectMapper objectMapper = new ObjectMapper();
//使用Jackson2JsonRedisSerializer來(lái)序列化和反序列化redis的value值(默認(rèn)使用JDK的序列化方式)
Jackson2JsonRedisSerializer<Object> jacksonSerial = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
// 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// null值字段不顯示
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 美化JSON輸出
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// 指定序列化輸入的類(lèi)型,類(lèi)必須是非final修飾的,final修飾的類(lèi),比如String,Integer等會(huì)跑出異常
objectMapper.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// jacksonSerial.setObjectMapper(objectMapper);
// 值采用json序列化
template.setValueSerializer(jacksonSerial);
// 使用StringRedisSerializer來(lái)序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 設(shè)置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
// template.setHashValueSerializer(jacksonSerial);
template.setHashValueSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
// 方式二
// @Bean
// public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// logger.info("開(kāi)始初始redis -->redisTemplate");
// RedisSerializer<Object> serializer = redisSerializer();
// RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// redisTemplate.setConnectionFactory(redisConnectionFactory);
// redisTemplate.setKeySerializer(new StringRedisSerializer());
// // 設(shè)置 redisTemplate 的序列化器
// redisTemplate.setValueSerializer(serializer);
// redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// redisTemplate.setHashValueSerializer(new StringRedisSerializer());
// redisTemplate.afterPropertiesSet();
// logger.info("初始redis完成 -->redisTemplate");
// return redisTemplate;
// }
//
// public RedisSerializer<Object> redisSerializer() {
// //創(chuàng)建JSON序列化器
// Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// objectMapper.activateDefaultTyping(
// LaissezFaireSubTypeValidator.instance,
// ObjectMapper.DefaultTyping.NON_FINAL,
// JsonTypeInfo.As.WRAPPER_ARRAY);
// serializer.setObjectMapper(objectMapper);
// return serializer;
// }
/**
* 對(duì)hash類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 對(duì)redis字符串類(lèi)型數(shù)據(jù)操作
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 對(duì)鏈表類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 對(duì)無(wú)序集合類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 對(duì)有序集合類(lèi)型的數(shù)據(jù)操作
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
五、Redis工具類(lèi)
在需要使用此工具類(lèi)的地址引入以下代碼進(jìn)行操作
@Autowired
private RedisUtil redisUtil;
package cn.keyidea.common.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis工具類(lèi)
*
* @author qyd
* @date 2024-05-20
*/
@Component
public class RedisUtil {
@Autowired
private final RedisTemplate<String, Object> redisTemplate;
public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
/**
* 刪除當(dāng)前庫(kù)所有key
*
* @return 返回刪除的key數(shù)
*/
public Long deleteAllKeys() {
Set<String> keys = redisTemplate.keys("*");
assert keys != null;
return redisTemplate.delete(keys);
}
/**
* 指定緩存失效時(shí)間
*
* @param key 鍵
* @param time 時(shí)間(秒)
* @return 返回結(jié)果
*/
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 獲取過(guò)期時(shí)間
*
* @param key 鍵 不能為null
* @return 時(shí)間(秒) 返回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 可以傳一個(gè)值 或多個(gè)
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) 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è)置時(shí)間
*
* @param key 鍵
* @param value 值
* @param time 時(shí)間(秒) time要大于0 如果time小于等于0 將設(shè)置無(wú)限期
* @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 返回結(jié)果
*/
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 返回結(jié)果
*/
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 項(xiàng) 不能為null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 獲取hashKey對(duì)應(yīng)的所有鍵值
*
* @param key 鍵
* @return 對(duì)應(yīng)的多個(gè)鍵值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 鍵
* @param map 對(duì)應(yīng)多個(gè)鍵值
* @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è)置時(shí)間
*
* @param key 鍵
* @param map 對(duì)應(yīng)多個(gè)鍵值
* @param time 時(shí)間(秒)
* @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 項(xiàng)
* @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 項(xiàng)
* @param value 值
* @param time 時(shí)間(秒) 注意:如果已存在的hash表有時(shí)間,這里將會(huì)替換原有的時(shí)間
* @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 項(xiàng) 可以使多個(gè) 不能為null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判斷hash表中是否有該項(xiàng)的值
*
* @param key 鍵 不能為null
* @param item 項(xiàng) 不能為null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash遞增 如果不存在,就會(huì)創(chuàng)建一個(gè) 并把新增后的值返回
*
* @param key 鍵
* @param item 項(xiàng)
* @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 項(xiàng)
* @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從一個(gè)set中查詢(xún),是否存在
*
* @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 值 可以是多個(gè)
* @return 成功個(gè)數(shù)
*/
public Long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 將set數(shù)據(jù)放入緩存
*
* @param key 鍵
* @param time 時(shí)間(秒)
* @param values 值 可以是多個(gè)
* @return 成功個(gè)數(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 0L;
}
}
/**
* 獲取set緩存的長(zhǎng)度
*
* @param key 鍵
* @return 返回結(jié)果
*/
public Long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 移除值為value的
*
* @param key 鍵
* @param values 值 可以是多個(gè)
* @return 移除的個(gè)數(shù)
*/
public Long setRemove(String key, Object... values) {
try {
return redisTemplate.opsForSet().remove(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
//===============================list=================================
/**
* 獲取list緩存的內(nèi)容
*
* @param key 鍵
* @param start 開(kāi)始
* @param end 結(jié)束 0 到 -1代表所有值
* @return 返回結(jié)果
*/
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緩存的長(zhǎng)度
*
* @param key 鍵
* @return
*/
public Long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
/**
* 通過(guò)索引 獲取list中的值
*
* @param key 鍵
* @param index 索引 index>=0時(shí), 0 表頭,1 第二個(gè)元素,依次類(lèi)推;index<0時(shí),-1,表尾,-2倒數(shù)第二個(gè)元素,依次類(lèi)推
* @return 返回結(jié)果
*/
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 返回結(jié)果
*/
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 時(shí)間(秒)
* @return 返回結(jié)果
*/
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 返回結(jié)果
*/
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 時(shí)間(秒)
* @return 返回結(jié)果
*/
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 返回結(jié)果
*/
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個(gè)值為value
*
* @param key 鍵
* @param count 移除多少個(gè)
* @param value 值
* @return 移除的個(gè)數(shù)
*/
public Long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
}
}