springboot整合redis詳解

java愛好者i發表於2019-03-30

springboot整合redis非常簡單

1、引入maven依賴redis包

org.springframework.boot spring-boot-starter-redis 2、application.yml配置檔案中配置redis環境

spring: redis: host: localhost #password: redispassword port: 6379 pool: max-idle: 100 min-idle: 1 max-active: 1000 max-wait: -1 3、書寫配置檔案RedisConfig

package com.kinder.redis; import java.lang.reflect.Method; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * 生成key的策略 * * @return / @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } /* * 管理快取 / @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); return rcm; } /* * RedisTemplate配置 */ @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } } 4、編寫redis的service的服務類

package com.kinder.redis; import java.io.Serializable; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.core.ZSetOperations; import org.springframework.stereotype.Service; @Service public class RedisService { @Autowired private RedisTemplate redisTemplate; /** * 寫入快取 * * @param key * @param value * @return / public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /* * 寫入快取設定時效時間 * * @param key * @param value * @return / public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /* * 批量刪除對應的value * * @param keys / public void remove(final String... keys) { for (String key : keys) { remove(key); } } /* * 批量刪除key * * @param pattern / public void removePattern(final String pattern) { Set keys = redisTemplate.keys(pattern); if (keys.size() > 0) redisTemplate.delete(keys); } /* * 刪除對應的value * * @param key / public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /* * 判斷快取中是否有對應的value * * @param key * @return / public boolean exists(final String key) { return redisTemplate.hasKey(key); } /* * 讀取快取 * * @param key * @return / public Object get(final String key) { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); return operations.get(key); } /* * 雜湊 新增 * * @param key * @param hashKey * @param value / public void hmSet(String key, Object hashKey, Object value) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); hash.put(key, hashKey, value); } /* * 雜湊獲取資料 * * @param key * @param hashKey * @return / public Object hmGet(String key, Object hashKey) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); return hash.get(key, hashKey); } /* * 列表新增 * * @param k * @param v / public void lPush(String k, Object v) { ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(k, v); } /* * 列表獲取 * * @param k * @param l * @param l1 * @return / public List lRange(String k, long l, long l1) { ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k, l, l1); } /* * 集合新增 * * @param key * @param value / public void add(String key, Object value) { SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key, value); } /* * 集合獲取 * * @param key * @return / public Set setMembers(String key) { SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } /* * 有序集合新增 * * @param key * @param value * @param scoure / public void zAdd(String key, Object value, double scoure) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key, value, scoure); } /* * 有序集合獲取 * * @param key * @param scoure * @param scoure1 * @return */ public Set rangeByScore(String key, double scoure, double scoure1) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rangeByScore(key, scoure, scoure1); } } 5、操作redis。

package com.kinder.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kinder.redis.RedisService; import com.kinder.util.ResultUtil; /**

  • redis操作
  • @author Administrator

/ @Controller @RequestMapping("/demo/redis") public class RedisController { @Autowired private RedisService redisService; /* * 設定Redis資料 * * @param key * @param value * @return / @RequestMapping("/setRedis.do") @ResponseBody public Object setRedis(String key, String value) { redisService.set(key, value); return ResultUtil.returnSuccess(); } /* * 根據key刪除Redis資料 * * @param key * @return / @RequestMapping("/delRedis.do") @ResponseBody public Object delRedis(String key) { redisService.remove(key); return ResultUtil.returnSuccess(); } /* * 根據key獲取Redis資料 * * @param key * @return */ @RequestMapping("/getRedis.do") @ResponseBody public Object getRedis(String key) { Object value = redisService.get(key); Map<String, Object> map = new HashMap<String, Object>(); map.put("value", value); return ResultUtil.returnSuccess(map); } } The end.

歡迎工作一到五年的Java工程師朋友們加入Java架構師:697558955

群內提供免費的Java架構學習資料(裡面有高可用、高併發、高效能及分散式、Jvm效能調優、Spring原始碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!

相關文章