文章目錄
- 前言
- 依賴
- 連接 Redis
- Redis 配置文件
- Redis 工具類
- 操作 Redis
- 創建 Redis 文件夾
- 查詢數據
- 遍歷 Redis 文件夾
前言
Redis 是一種高性能的鍵值存儲數據庫,支持網絡、可基于內存亦可持久化的日志型,而 Spring Boot 是一個簡化了開發過程的 Java 框架。將兩者結合,可以輕松地在 Spring Boot 項目中使用 Redis 來實現數據緩存、會話管理和分布式鎖等功能。
Redis 本身是一個內存數據庫,在應用中可以充當緩存,提高系統數據查詢性能。
一般用于在較短的時間段對相同數據頻繁讀取的場合,將讀取頻度較高的數據放入緩存,直接從緩存取數據,以提高效率。
使用場景如:實時排名、秒殺系統等等,并可設置數據自動過期,大大提高效率。
依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
連接 Redis
application.yml
配置文件
spring:data:redis:# Redis服務器地址host: localhost# Redis服務器端口,默認為6379port: 6379# Redis連接的數據庫,默認為0(Redis默認有16個數據庫,0~15)database: 0# Redis服務器連接密碼,默認為空password:# 連接超時時間(毫秒)timeout: 2000jedis:pool:# 連接池最大連接數,若為負值則表示沒有任何限制max-active: 10# 連接池中的最大空閑連接max-idle: 6# 連接池中的最小空閑連接min-idle: 2# 連接池最大阻塞等待時間,若為負值則表示沒有任何限制max-wait: 1000lettuce:# 超時時間關閉shutdown-timeout: 100
Redis 配置文件
新建Redis配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;/*** Redis 配置*/
@Configuration
public class RedisConfig {/*** Redis 序列化配置*/@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(connectionFactory);// 使用GenericJackson2JsonRedisSerializer替換默認序列化GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();// 設置 Key 和 Value 的序列化規則redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// 初始化 RedisTemplate 序列化完成redisTemplate.afterPropertiesSet();return redisTemplate;}}
Redis 工具類
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.*;
import java.util.concurrent.TimeUnit;/*** spring redis 工具類**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {@Autowiredpublic RedisTemplate redisTemplate;/*** 緩存基本的對象,Integer、String、實體類等** @param key 緩存的鍵值* @param value 緩存的值*/public <T> void setCacheObject(final String key, final T value) {redisTemplate.opsForValue().set(key, value);}/*** 緩存基本的對象,Integer、String、實體類等** @param key 緩存的鍵值* @param value 緩存的值* @param timeout 時間* @param timeUnit 時間顆粒度*/public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 設置有效時間** @param key Redis鍵* @param timeout 超時時間* @return true=設置成功;false=設置失敗*/public boolean expire(final String key, final long timeout) {return expire(key, timeout, TimeUnit.SECONDS);}/*** 設置有效時間** @param key Redis鍵* @param timeout 超時時間* @param unit 時間單位* @return true=設置成功;false=設置失敗*/public boolean expire(final String key, final long timeout, final TimeUnit unit) {return redisTemplate.expire(key, timeout, unit);}/*** 獲取有效時間** @param key Redis鍵* @return 有效時間*/public long getExpire(final String key) {return redisTemplate.getExpire(key);}/*** 判斷 key是否存在** @param key 鍵* @return true 存在 false不存在*/public Boolean hasKey(String key) {return redisTemplate.hasKey(key);}/*** 獲得緩存的基本對象。** @param key 緩存鍵值* @return 緩存鍵值對應的數據*/public <T> T getCacheObject(final String key) {ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 刪除單個對象** @param key*/public boolean deleteObject(final String key) {return redisTemplate.delete(key);}/*** 刪除集合對象** @param collection 多個對象* @return*/public boolean deleteObject(final Collection collection) {return redisTemplate.delete(collection) > 0;}/*** 緩存List數據** @param key 緩存的鍵值* @param dataList 待緩存的List數據* @return 緩存的對象*/public <T> long setCacheList(final String key, final List<T> dataList) {Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count == null ? 0 : count;}/*** 獲得緩存的list對象** @param key 緩存的鍵值* @return 緩存鍵值對應的數據*/public <T> List<T> getCacheList(final String key) {return redisTemplate.opsForList().range(key, 0, -1);}/*** 緩存Set** @param key 緩存鍵值* @param dataSet 緩存的數據* @return 緩存數據的對象*/public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while (it.hasNext()) {setOperation.add(it.next());}return setOperation;}/*** 獲得緩存的set** @param key* @return*/public <T> Set<T> getCacheSet(final String key) {return redisTemplate.opsForSet().members(key);}/*** 緩存Map** @param key* @param dataMap*/public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {if (dataMap != null) {redisTemplate.opsForHash().putAll(key, dataMap);}}/*** 獲得緩存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(final String key) {return redisTemplate.opsForHash().entries(key);}/*** 往Hash中存入數據** @param key Redis鍵* @param hKey Hash鍵* @param value 值*/public <T> void setCacheMapValue(final String key, final String hKey, final T value) {redisTemplate.opsForHash().put(key, hKey, value);}/*** 獲取Hash中的數據** @param key Redis鍵* @param hKey Hash鍵* @return Hash中的對象*/public <T> T getCacheMapValue(final String key, final String hKey) {HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/*** 獲取多個Hash中的數據** @param key Redis鍵* @param hKeys Hash鍵集合* @return Hash對象集合*/public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {return redisTemplate.opsForHash().multiGet(key, hKeys);}/*** 刪除Hash中的某條數據** @param key Redis鍵* @param hKey Hash鍵* @return 是否成功*/public boolean deleteCacheMapValue(final String key, final String hKey) {return redisTemplate.opsForHash().delete(key, hKey) > 0;}/*** 獲得緩存的基本對象列表** @param pattern 字符串前綴* @return 對象列表*/public Collection<String> keys(final String pattern) {return redisTemplate.keys(pattern);}
}
操作 Redis
創建 Redis 文件夾
編寫測試用例
以 :
分割字符串即可創建文件夾,示例如下:
import com.chh.api.utils.redis.RedisCache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RedisTest {@Autowiredprivate RedisCache redisCache;@Testvoid contextLoads() {redisCache.setCacheObject(getCacheKey("test"), "測試");}/*** 設置cache key** @param configKey 參數鍵* @return 緩存鍵key*/public static String getCacheKey(String configKey) {return "chh-api:data:" + configKey;}
}
運行測試用例,效果如圖:
只有一條數據的時候,不顯示文件夾
再寫入一條數據,key命名為test2
@Testvoid contextLoads() {redisCache.setCacheObject(getCacheKey("test2"), "測試2");}
運行測試用例,效果如圖:
查詢數據
@Testvoid getData() {// 判斷鍵是否存在if (redisCache.hasKey("chh-api:data:test")) {Object object = redisCache.getCacheObject("chh-api:data:test");System.out.println(object);} else {System.out.println("不存在");}}
運行測試用例,效果如圖:
遍歷 Redis 文件夾
@Testvoid getAllData() {Collection<String> keys = redisCache.keys("chh-api:data:*");for (String key : keys) {Object object = redisCache.getCacheObject(key);System.out.println(object);}}
運行測試用例,效果如圖: