springBoot整合redis使用案例詳解
一、創(chuàng)建springboot項(xiàng)目(采用骨架方式)






創(chuàng)建完成;
我們分析下pom文件中內(nèi)容:
所使用到的關(guān)鍵依賴:
<!--springBoot集成redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
二、配置文件
server.port=8088 spring.redis.host=127.0.0.1 #Redis服務(wù)器連接端口 spring.redis.port=6379 #Redis服務(wù)器連接密碼(默認(rèn)為空) spring.redis.password=123456 #連接池最大連接數(shù)(使用負(fù)值表示沒有限制) spring.redis.pool.max-active=8 #連接池最大阻塞等待時間(使用負(fù)值表示沒有限制) spring.redis.pool.max-wait=-1 #連接池中的最大空閑連接 spring.redis.pool.max-idle=8 #連接池中的最小空閑連接 spring.redis.pool.min-idle=0 #連接超時時間(毫秒) spring.redis.timeout=30000
三、使用redis
package com.example.redis.cache;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author wxl
* @date 2021-08-15 18:44
*/
@Slf4j
@Component
public class CacheService {
@Autowired
private StringRedisTemplate redisTemplate;
private final String DEFAULT_KEY_PREFIX = "";
private final int EXPIRE_TIME = 1;
private final TimeUnit EXPIRE_TIME_TYPE = TimeUnit.DAYS;
/**
* 數(shù)據(jù)緩存至redis
*
* @param key
* @param value
* @return
*/
public <K, V> void add(K key, V value) {
try {
if (value != null) {
redisTemplate
.opsForValue()
.set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("數(shù)據(jù)緩存至redis失敗");
}
}
/**
* 數(shù)據(jù)緩存至redis并設(shè)置過期時間
*
* @param key
* @param value
* @return
*/
public <K, V> void add(K key, V value, long timeout, TimeUnit unit) {
try {
if (value != null) {
redisTemplate
.opsForValue()
.set(DEFAULT_KEY_PREFIX + key, JSON.toJSONString(value), timeout, unit);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("數(shù)據(jù)緩存至redis失敗");
}
}
/**
* 寫入 hash-set,已經(jīng)是key-value的鍵值,不能再寫入為hash-set
*
* @param key must not be {@literal null}.
* @param subKey must not be {@literal null}.
* @param value 寫入的值
*/
public <K, SK, V> void addHashCache(K key, SK subKey, V value) {
redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value);
}
/**
* 寫入 hash-set,并設(shè)置過期時間
*
* @param key must not be {@literal null}.
* @param subKey must not be {@literal null}.
* @param value 寫入的值
*/
public <K, SK, V> void addHashCache(K key, SK subKey, V value, long timeout, TimeUnit unit) {
redisTemplate.opsForHash().put(DEFAULT_KEY_PREFIX + key, subKey, value);
redisTemplate.expire(DEFAULT_KEY_PREFIX + key, timeout, unit);
}
/**
* 獲取 hash-setvalue
*
* @param key must not be {@literal null}.
* @param subKey must not be {@literal null}.
*/
public <K, SK> Object getHashCache(K key, SK subKey) {
return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey);
}
/**
* 從redis中獲取緩存數(shù)據(jù),轉(zhuǎn)成對象
*
* @param key must not be {@literal null}.
* @param clazz 對象類型
* @return
*/
public <K, V> V getObject(K key, Class<V> clazz) {
String value = this.get(key);
V result = null;
if (!StringUtils.isEmpty(value)) {
result = JSONObject.parseObject(value, clazz);
}
return result;
}
/**
* 從redis中獲取緩存數(shù)據(jù),轉(zhuǎn)成list
*
* @param key must not be {@literal null}.
* @param clazz 對象類型
* @return
*/
public <K, V> List<V> getList(K key, Class<V> clazz) {
String value = this.get(key);
List<V> result = Collections.emptyList();
if (!StringUtils.isEmpty(value)) {
result = JSONArray.parseArray(value, clazz);
}
return result;
}
/**
* 功能描述:Get the value of {@code key}.
*
* @param key must not be {@literal null}.
* @return java.lang.String
* @date 2021/9/19
**/
public <K> String get(K key) {
String value;
try {
value = redisTemplate.opsForValue().get(DEFAULT_KEY_PREFIX + key);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException("從redis緩存中獲取緩存數(shù)據(jù)失敗");
}
return value;
}
/**
* 刪除key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 批量刪除key
*/
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
/**
* 序列化key
*/
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
/**
* 是否存在key
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 設(shè)置過期時間
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 設(shè)置過期時間
*/
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
/**
* 移除 key 的過期時間,key 將持久保持
*/
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的過期時間
*/
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的剩余的過期時間
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
}
1、添加字符串到redis
/**
* 功能描述:添加字符串到redis
*/
@Test
void add() {
cacheService.add("test", 1234);
}
結(jié)果:

2、將對象轉(zhuǎn)換成jsonString并存入redis
/**
* 功能描述:添加對象至redis
*/
@Test
void addObject() {
User user = User.builder()
.id(ID)
.name("小萌")
.age(AGE)
.build();
cacheService.add(user.getId(), user);
}
結(jié)果:

3、將對象集合轉(zhuǎn)換成jsonString,并設(shè)置過期時間存入至redis
/**
* 功能描述:添加對象集合至redis
*/
@Test
void addObjects() {
ArrayList<User> users = new ArrayList<>();
User user = User.builder()
.id(ID)
.name("小萌")
.age(AGE)
.build();
users.add(user);
cacheService.add("key", users, 1, TimeUnit.HOURS);
}
結(jié)果:

4、獲取對象
/**
* 功能描述:獲取對象
*/
@Test
void getObject() {
User object = cacheService.getObject(ID, User.class);
System.out.println("object = " + object);
}
結(jié)果:
object = User(id=123, name=小萌, age=12)
5、獲取對象集合
/**
* 功能描述:獲取對象集合
*/
@Test
void getObjects() {
List<User> users = cacheService.getList("key", User.class);
System.out.println("users = " + users);
}
結(jié)果:
users = [User(id=123, name=小萌, age=12)]
6、添加 hash-set
/**
* 功能描述:添加 hash-set
*/
@Test
void addHashCache() {
cacheService.addHashCache("hashKey", "key", "value");
}
結(jié)果:

7、獲取 hash-setvalue
/**
* 獲取 hash-setvalue
*
* @param key must not be {@literal null}.
* @param subKey must not be {@literal null}.
*/
public <K, SK> Object getHashCache(K key, SK subKey) {
return redisTemplate.opsForHash().get(DEFAULT_KEY_PREFIX + key, subKey);
}
結(jié)果:
hashCache = value
到此這篇關(guān)于springBoot整合redis使用案例詳解的文章就介紹到這了,更多相關(guān)springBoot整合redis使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解析Java中所有錯誤和異常的父類java.lang.Throwable
這篇文章主要介紹了Java中所有錯誤和異常的父類java.lang.Throwable,文章中簡單地分析了其源碼,說明在代碼注釋中,需要的朋友可以參考下2016-03-03
MyBatisPlus 主鍵策略的實(shí)現(xiàn)(4種)
MyBatis Plus 集成了多種主鍵策略,幫助用戶快速生成主鍵,本文主要介紹了MyBatisPlus主鍵策略的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10
詳解Jenkins 實(shí)現(xiàn)Gitlab事件自動觸發(fā)Jenkins構(gòu)建及釘釘消息推送
這篇文章主要介紹了Jenkins 實(shí)現(xiàn)Gitlab事件自動觸發(fā)Jenkins構(gòu)建及釘釘消息推送,應(yīng)該會對大家學(xué)習(xí)Jenkins有所啟發(fā)2021-04-04
Java利用Socket類實(shí)現(xiàn)TCP通信程序
TCP通信能實(shí)現(xiàn)兩臺計(jì)算機(jī)之間的數(shù)據(jù)交互,通信的兩端,要嚴(yán)格區(qū)分為客戶端與服務(wù)端,下面我們就來看看Java如何利用Socket類實(shí)現(xiàn)TCP通信程序吧2024-02-02
java 使用poi 導(dǎo)入Excel數(shù)據(jù)到數(shù)據(jù)庫的步驟
這篇文章主要介紹了java 使用poi 導(dǎo)入Excel 數(shù)據(jù)到數(shù)據(jù)庫的步驟,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12
java gui實(shí)現(xiàn)計(jì)算器小程序
這篇文章主要為大家詳細(xì)介紹了java gui實(shí)現(xiàn)計(jì)算器小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié)
這篇文章主要介紹了Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié),多態(tài)是繼封裝、繼承之后,面向?qū)ο蟮牡谌筇匦?,本文只總結(jié)了多態(tài)的實(shí)現(xiàn)原理,需要的朋友可以參考一下2022-06-06

