springboot整合redis詳解

來源:互聯網
上載者:User

標籤:over   work   request   stringbu   cache   redis   void   stack   zset   

歡迎掃碼加入Java高知群交流


springboot整合redis非常簡單

1、引入maven依賴redis包

 

<!--  springboot整合 redis --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-redis</artifactId></dependency>


 

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@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {/** * 產生key的策略 *  * @return */@Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic 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();}};}/** * 管理緩衝 */@Beanpublic CacheManager cacheManager(RedisTemplate redisTemplate) {RedisCacheManager rcm = new RedisCacheManager(redisTemplate);return rcm;}/** * RedisTemplate配置 */@Beanpublic 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;@Servicepublic class RedisService {@Autowiredprivate 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<Serializable> 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<Object> 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<Object> 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<Object> 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 {@Autowiredprivate RedisService redisService;/** * 設定Redis資料 *  * @param key * @param value * @return */@RequestMapping("/setRedis.do")@ResponseBodypublic Object setRedis(String key, String value) {redisService.set(key, value);return ResultUtil.returnSuccess();}/** * 根據key刪除Redis資料 *  * @param key * @return */@RequestMapping("/delRedis.do")@ResponseBodypublic Object delRedis(String key) {redisService.remove(key);return ResultUtil.returnSuccess();}/** * 根據key擷取Redis資料 *  * @param key * @return */@RequestMapping("/getRedis.do")@ResponseBodypublic 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高知群交流


springboot整合redis詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.