SpringBoot整合Redis完整篇
1、在springboot項目的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/></parent><groupId>com.example</groupId><artifactId>spring-boot-redis</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-redis</name><description>spring-boot-redis</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
2、在application.properties中配置redis參數
# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.jedis.pool.max-active=10
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 連接池中的最大空閑連接
spring.redis.jedis.pool.max-idle=10
# 連接池中的最小空閑連接
spring.redis.jedis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=1000ms
3、Redis的配置類
Spring 封裝了RedisTemplate<K,V>
對象來操作redis。
Spring在org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
類下配置的兩
個RedisTemplate
的Bean。
RedisTemplate<Object, Object>
這個Bean使用JdkSerializationRedisSerializer
進行序列化,即key, value需要實現Serializable
接口,
redis數據格式比較難懂。
StringRedisTemplate,即RedisTemplate<String, String>
key和value都是String。當需要存儲實體類時,需要先轉為String,再存入Redis。一般轉為Json格式的字符串,所
以使用StringRedisTemplate,需要手動將實體類轉為Json格式。
ValueOperations<String, String> valueTemplate = stringTemplate.opsForValue();
Gson gson = new Gson();valueTemplate.set("StringKey1", "hello spring boot redis, String Redis");
String value = valueTemplate.get("StringKey1");
System.out.println(value);valueTemplate.set("StringKey2", gson.toJson(new Person("theName", 11)));
Person person = gson.fromJson(valueTemplate.get("StringKey2"), Person.class);
System.out.println(person);
Spring配置的兩個RedisTemplate
都不太方便使用,所以可以配置一個RedisTemplate<String,Object>
的
Bean,key使用String即可(包括Redis Hash 的key),value存取Redis時默認使用Json格式轉換。
package com.example.springbootredisuse1.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.net.UnknownHostException;/*** @author zhangshixing* @date 2021年11月06日 9:44* redis 配置類*/
@Configuration
public class RedisConfig {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)throws UnknownHostException {// 定義Jackson2JsonRedisSerializer序列化對象Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);ObjectMapper om = new ObjectMapper();// 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和publicom.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);// 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會報異常om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);// 創建RedisTemplate<String, Object>對象RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();// 配置連接工廠template.setConnectionFactory(redisConnectionFactory);StringRedisSerializer stringSerial = new StringRedisSerializer();// redis key 序列化方式使用stringSerialtemplate.setKeySerializer(stringSerial);// redis value 序列化方式使用jacksontemplate.setValueSerializer(jackson2JsonRedisSerializer);// redis hash key 序列化方式使用stringSerialtemplate.setHashKeySerializer(stringSerial);// redis hash value 序列化方式使用jacksontemplate.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}
}
4、Redis的工具類
package com.example.springbootredisuse1.utils;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;/*** @author zhangshixing* @date 2021年11月06日 9:46* redis 工具類*/
@Component
public class RedisUtils {/*** 日志對象*/private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);@Autowiredprivate RedisTemplate<String, Object> redisTemplate;/*** 指定緩存失效時間** @param key 鍵* @param time 時間(秒)* @return*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {logger.error("RedisUtils expire(String key,long time) failure." + e.getMessage());return false;}}/*** 根據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) {logger.error("RedisUtils hasKey(String key) failure." + e.getMessage());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((Collection<String>) CollectionUtils.arrayToList(key));}}}/*** 普通緩存獲取** @param key 鍵* @return 值*/public Object get(String key) {System.out.println(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) {logger.error("RedisUtils set(String key,Object value) failure." + e.getMessage());return false;}}/*** 普通緩存放入并設置時間** @param key 鍵* @param value 值* @param time 時間(秒) time要大于0 如果time小于等于0 將設置無限期* @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) {logger.error("RedisUtils set(String key,Object value,long time) failure." + e.getMessage());return false;}}/*** 遞增** @param key 鍵* @param delta* @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);}/*** HashGet** @param key 鍵 不能為null* @param item 項 不能為null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 獲取hashKey對應的所有鍵值** @param key 鍵* @return 對應的多個鍵值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet** @param key 鍵* @param map 對應多個鍵值* @return true 成功 false 失敗*/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {logger.error("RedisUtils hmset(String key, Map<String,Object> map) failure." + e.getMessage());return false;}}/*** HashSet 并設置時間** @param key 鍵* @param map 對應多個鍵值* @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) {logger.error("RedisUtils hmset(String key, Map<String,Object> map, long time) failure." + e.getMessage());return false;}}/*** 向一張hash表中放入數據,如果不存在將創建** @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) {logger.error("RedisUtils hset(String key,String item,Object value) failure." + e.getMessage());return false;}}/*** 向一張hash表中放入數據,如果不存在將創建** @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) {logger.error("RedisUtils hset(String key,String item,Object value,long time) failure." + e.getMessage());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遞增 如果不存在,就會創建一個 并把新增后的值返回** @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);}/*** 根據key獲取Set中的所有值** @param key 鍵* @return*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {logger.error("RedisUtils sGet(String key) failure." + e.getMessage());return null;}}/*** 根據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) {logger.error("RedisUtils sHasKey(String key,Object value) failure." + e.getMessage());return false;}}/*** 將數據放入set緩存** @param key 鍵* @param values 值 可以是多個* @return 成功個數*/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {logger.error("RedisUtils sSet(String key, Object...values) failure." + e.getMessage());return 0;}}/*** 將set數據放入緩存** @param key 鍵* @param time 時間(秒)* @param values 值 可以是多個* @return 成功個數*/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) {logger.error("RedisUtils sSetAndTime(String key,long time,Object...values) failure." + e.getMessage());return 0;}}/*** 獲取set緩存的長度** @param key 鍵* @return*/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {logger.error("RedisUtils sGetSetSize(String key) failure." + e.getMessage());return 0;}}/*** 移除值為value的** @param key 鍵* @param values 值 可以是多個* @return 移除的個數*/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {logger.error("RedisUtils setRemove(String key, Object ...values) failure." + e.getMessage());return 0;}}/*** 獲取list緩存的內容** @param key 鍵* @param start 開始* @param end 結束 0 到 -1代表所有值* @return*/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {logger.error("RedisUtils lGet(String key, long start, long end) failure." + e.getMessage());return null;}}/*** 獲取list緩存的長度** @param key 鍵* @return*/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {logger.error("RedisUtils lGetListSize(String key) failure." + e.getMessage());return 0;}}/*** 通過索引 獲取list中的值** @param key 鍵* @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推* @return*/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {logger.error("RedisUtils lGetIndex(String key,long index) failure." + e.getMessage());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) {logger.error("RedisUtils lSet(String key, Object value) failure." + e.getMessage());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) {logger.error("RedisUtils lSet(String key, Object value, long time) failure." + e.getMessage());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) {logger.error("RedisUtils lSet(String key, List<Object> value) failure." + e.getMessage());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) {logger.error("RedisUtils lSet(String key, List<Object> value, long time) failure." + e.getMessage());return false;}}/*** 根據索引修改list中的某條數據** @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) {logger.error("RedisUtils lUpdateIndex(String key, long index,Object value) failure." + e.getMessage());return false;}}/*** 移除N個值為value** @param key 鍵* @param count 移除多少個* @param value 值* @return 移除的個數*/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {logger.error("RedisUtils lRemove(String key,long count,Object value) failure." + e.getMessage());return 0;}}
}
5、RedisController
package com.example.springbootredisuse1.controller;import com.example.springbootredisuse1.utils.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** @author zhangshixing* @date 2021年11月07日 10:23*/
@RequestMapping("/redis")
@RestController
public class RedisController {// redis中存儲的過期時間60sprivate static int ExpireTime = 60;@Resourceprivate RedisUtils redisUtil;@RequestMapping("set")public boolean redisset(String key, String value) {return redisUtil.set(key, value);}@RequestMapping("get")public Object redisget(String key) {return redisUtil.get(key);}@RequestMapping("expire")public boolean expire(String key) {return redisUtil.expire(key, ExpireTime);}
}
6、啟動類
package com.example.springbootredisuse1;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBootRedisApplication {public static void main(String[] args) {SpringApplication.run(SpringBootRedisApplication.class, args);}}
7、測試
用的Postman工具測試,也可以用瀏覽器或其他工具測試。
1.添加鍵值
返回:true 代表向redis中存成功
2.獲取鍵值
3.設置過期時間
過期時間為60s,60s后再次查詢:
發現該鍵已經過期,值為空。