自己整理了 spring boot 結合 Redis 的工具類
引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
加入配置
# Redis資料庫索引(預設為0)
spring.redis.database=0
# Redis伺服器位址
spring.redis.host=localhost
# Redis伺服器連接配接端口
spring.redis.port=6379
推薦一個交流學習群:614478470 裡面會分享一些資深架構師錄制的視訊錄像:有Spring,MyBatis,Netty源碼分析,高并發、高性能、分布式、微服務架構的原理,JVM性能優化這些成為架構師必備的知識體系。還能領取免費的學習資源,目前受益良多
點選:加入
實作代碼
這裡用到了 靜态類工具類中 如何使用 @Autowired
package com.lmxdawn.api.common.utils;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* 緩存操作類
*/
@Component
public class CacheUtils {
@Autowired
private RedisTemplate<String, String> redisTemplate;
// 維護一個本類的靜态變量
private static CacheUtils cacheUtils;
@PostConstruct
public void init() {
cacheUtils = this;
cacheUtils.redisTemplate = this.redisTemplate;
}
/**
* 将參數中的字元串值設定為鍵的值,不設定過期時間
* @param key
* @param value 必須要實作 Serializable 接口
*/
public static void set(String key, String value) {
cacheUtils.redisTemplate.opsForValue().set(key, value);
* 将參數中的字元串值設定為鍵的值,設定過期時間
* @param timeout
public static void set(String key, String value, Long timeout) {
cacheUtils.redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
* 擷取與指定鍵相關的值
* @return
public static Object get(String key) {
return cacheUtils.redisTemplate.opsForValue().get(key);
* 設定某個鍵的過期時間
* @param key 鍵值
* @param ttl 過期秒數
public static boolean expire(String key, Long ttl) {
return cacheUtils.redisTemplate.expire(key, ttl, TimeUnit.SECONDS);
* 判斷某個鍵是否存在
public static boolean hasKey(String key) {
return cacheUtils.redisTemplate.hasKey(key);
* 向集合添加元素
* @param value
* @return 傳回值為設定成功的value數
public static Long sAdd(String key, String... value) {
return cacheUtils.redisTemplate.opsForSet().add(key, value);
* 擷取集合中的某個元素
* @return 傳回值為redis中鍵值為key的value的Set集合
public static Set<String> sGetMembers(String key) {
return cacheUtils.redisTemplate.opsForSet().members(key);
* 将給定分數的指定成員添加到鍵中存儲的排序集合中
* @param score
public static Boolean zAdd(String key, String value, double score) {
return cacheUtils.redisTemplate.opsForZSet().add(key, value, score);
* 傳回指定排序集中給定成員的分數
public static Double zScore(String key, String value) {
return cacheUtils.redisTemplate.opsForZSet().score(key, value);
* 删除指定的鍵
public static Boolean delete(String key) {
return cacheUtils.redisTemplate.delete(key);
* 删除多個鍵
* @param keys
public static Long delete(Collection<String> keys) {
return cacheUtils.redisTemplate.delete(keys);
}
推薦一個交流學習群,裡面會分享一些資深架構師錄制的視訊錄像:有Spring,MyBatis,Netty源碼分析,高并發、高性能、分布式、微服務架構的原理,JVM性能優化這些成為架構師必備的知識體系。還能領取免費的學習資源,目前受益良多
點選: 加入