SpringBoot配置Redis實現保存獲取和刪除數據
Redis 是完全開源的,遵守 BSD 協議,是一個高性能的 key-value 數據庫。
Redis 與其他 key - value 緩存產品有以下三個特點:
(1)Redis支持數據的持久化,可以將內存中的數據保存在磁盤中,重啟的時候可以再次加載進行使用。
(2)Redis不僅僅支持簡單的key-value類型的數據,同時還提供list,set,zset,hash等數據結構的存儲。
(2)Redis支持數據的備份,即master-slave模式的數據備份。
2 Maven依賴<!--redis緩存--><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency> <!-- 阿里JSON解析器 --><dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version></dependency>3 application.propertis
# 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=20# 連接池最大阻塞等待時間(使用負值表示沒有限制)spring.redis.jedis.pool.max-wait=-1# 連接池中的最大空閑連接spring.redis.jedis.pool.max-idle=10# 連接池中的最小空閑連接spring.redis.jedis.pool.min-idle=0# 連接超時時間(毫秒)spring.redis.timeout=10004 RedisConfig
Redis配置文件。
package com.config; import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;import org.springframework.context.annotation.*;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer; @Configurationpublic class RedisConfig { @Bean @SuppressWarnings(value = { 'unchecked', 'rawtypes' }) public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory); FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);// 使用StringRedisSerializer來序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer); // Hash的key也采用StringRedisSerializer的序列化方式template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer); template.afterPropertiesSet();return template; }}5 RedisService
Redis基本操作方法。
package com.service; 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.Service; import java.util.*;import java.util.concurrent.TimeUnit; @Servicepublic class RedisService { @Autowired private 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 緩存鍵值 * @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 long deleteObject(final Collection collection) {return redisTemplate.delete(collection); } /** * 緩存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); } /** * 獲得緩存的基本對象列表 * * @param pattern 字符串前綴 * @return 對象列表 */ public Collection<String> keys(final String pattern) {return redisTemplate.keys(pattern); }}6 調試代碼
package com.controller; import com.service.RedisService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*; @RestController@RequestMapping('/redis')public class RedisController { @Autowired private RedisService redisService; /** * 保存Redis數據 * * @param key * @param value * @return */ @PostMapping('/setValue/{key}/{value}') public String setValue(@PathVariable('key') String key, @PathVariable('value') String value) {redisService.setCacheObject(key, value);return '保存成功'; } /** * 獲取Redis數據 * * @param key * @return */ @GetMapping('/getValue') public String getValue(@RequestParam String key) {return redisService.getCacheObject(key); } /** * 刪除Redis數據 * * @param key * @return */ @DeleteMapping('/deleteValue/{key}') public String deleteValue(@PathVariable('key') String key) {return redisService.deleteObject(key) ? '刪除成功' : '刪除失敗'; }}7 調試結果
保存數據:
獲取數據:
刪除數據:
到此這篇關于SpringBoot配置Redis實現保存獲取和刪除數據的文章就介紹到這了,更多相關SpringBoot Redis保存獲取和刪除數據內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: