佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 使用SpringBoot集成redis的方法

使用SpringBoot集成redis的方法

熱門標(biāo)簽:鐵路電話系統(tǒng) 百度競價(jià)排名 AI電銷 Linux服務(wù)器 呼叫中心市場需求 服務(wù)外包 地方門戶網(wǎng)站 網(wǎng)站排名優(yōu)化

今天,日月在這里教大家如何使用springBoot集成redis,說實(shí)話比較簡單,網(wǎng)上也有大把的教程。先套用一下網(wǎng)上的簡介。
定義

REmote DIctionary Server(Redis) 是一個由Salvatore Sanfilippo寫的key-value存儲系統(tǒng)。
Redis是一個開源的使用ANSI C語言編寫、遵守BSD協(xié)議、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API。
它通常被稱為數(shù)據(jù)結(jié)構(gòu)服務(wù)器,因?yàn)橹担╲alue)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等類型。
reids的優(yōu)點(diǎn)

以下是Redis的一些優(yōu)點(diǎn)。

異???- Redis非常快,每秒可執(zhí)行大約110000次的設(shè)置(SET)操作,每秒大約可執(zhí)行81000次的讀取/獲取(GET)操作。
支持豐富的數(shù)據(jù)類型 - Redis支持開發(fā)人員常用的大多數(shù)數(shù)據(jù)類型,例如列表,集合,排序集和散列等等。這使得Redis很容易被用來解決各種問題,因?yàn)槲覀冎滥男﹩栴}可以更好使用地哪些數(shù)據(jù)類型來處理解決。
操作具有原子性 - 所有Redis操作都是原子操作,這確保如果兩個客戶端并發(fā)訪問,Redis服務(wù)器能接收更新的值。
多實(shí)用工具 - Redis是一個多實(shí)用工具,可用于多種用例,如:緩存,消息隊(duì)列(Redis本地支持發(fā)布/訂閱),應(yīng)用程序中的任何短期數(shù)據(jù),例如,web應(yīng)用程序中的會話,網(wǎng)頁命中計(jì)數(shù)等。

Redis 安裝

Window 下安裝
下載地址:https://github.com/MSOpenTech/redis/releases。
Redis 支持 32 位和 64 位。這個需要根據(jù)你系統(tǒng)平臺的實(shí)際情況選擇,這里我們下載 Redis-x64-xxx.zip壓縮包到 C 盤,解壓后,將文件夾重新命名為 redis。

打開一個 cmd 窗口 使用cd命令切換目錄到 C:\redis
運(yùn)行 redis-server.exe redis.windows.conf
如果想方便的話,可以把 redis 的路徑加到系統(tǒng)的環(huán)境變量里,這樣就省得再輸路徑了,后面的那個 redis.windows.conf 可以省略,如果省略,會啟用默認(rèn)的。輸入之后,會顯示如下界面:

集成redis

我們還是延用上一章的項(xiàng)目:Springboot集成springcloud-config實(shí)現(xiàn)dataSource熱部署

1、添加依賴

!--集成redis-->
dependency>
 groupId>org.springframework.boot/groupId>
 artifactId>spring-boot-starter-redis/artifactId>
 version>1.4.1.RELEASE/version>
/dependency>
dependency>
 groupId>com.alibaba/groupId>
 artifactId>fastjson/artifactId>
 version>1.2.3/version>
/dependency>
dependency>
 groupId>com.fasterxml.jackson.core/groupId>
 artifactId>jackson-databind/artifactId>
/dependency>

2、在配置中心里添加redis配置

spring.redis.host=127.0.0.1
#Redis服務(wù)器連接端口
spring.redis.port=6379
#Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
#連接池最大連接數(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

3、配置類RedisConfig

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
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.cloud.context.config.annotation.RefreshScope;
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.connection.jedis.JedisConnectionFactory;
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.PropertyAccessor; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
public class RedisConfig extends CachingConfigurerSupport{
 @Value("${spring.redis.host}")
 private String host;
 @Value("${spring.redis.port}")
 private int port;
 @Value("${spring.redis.timeout}")
 private int timeout;
 @Value("${spring.redis.password}")
 private String password;
 @Value("${spring.redis.pool.max-active}")
 private int maxActive;
 @Value("${spring.redis.pool.max-wait}")
 private int maxWait;
 @Value("${spring.redis.pool.max-idle}")
 private int maxIdle;
 @Value("${spring.redis.pool.min-idle}")
 private int minIdle;
 
 @RefreshScope
 @Bean
 public KeyGenerator wiselyKeyGenerator(){
 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();
 }
 };
 }
 
 @RefreshScope
 @Bean
 public JedisConnectionFactory redisConnectionFactory() {
 JedisConnectionFactory factory = new JedisConnectionFactory();
 factory.setHostName(host);
 factory.setPort(port);
 factory.setTimeout(timeout); //設(shè)置連接超時時間
 factory.setPassword(password);
 factory.getPoolConfig().setMaxIdle(maxIdle);
 factory.getPoolConfig().setMinIdle(minIdle);
 factory.getPoolConfig().setMaxTotal(maxActive);
 factory.getPoolConfig().setMaxWaitMillis(maxWait);
 return factory;
 }
 
 @RefreshScope
 @Bean
 public CacheManager cacheManager(RedisTemplate redisTemplate) {
 RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
 // Number of seconds before expiration. Defaults to unlimited (0)
 cacheManager.setDefaultExpiration(10); //設(shè)置key-value超時時間
 return cacheManager;
 }
 
 @RefreshScope
 @Bean
 public RedisTemplateString, String> redisTemplate(RedisConnectionFactory factory) {
 StringRedisTemplate template = new StringRedisTemplate(factory);
 setSerializer(template); //設(shè)置序列化工具,這樣ReportBean不需要實(shí)現(xiàn)Serializable接口
 template.afterPropertiesSet();
 return template;
 }
 
 @RefreshScope
 private void setSerializer(StringRedisTemplate template) {
 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);
 }
}

4、RedisUtils類

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 RedisUtils {
 @Autowired
 private RedisTemplate redisTemplate;
 /**
 * 寫入緩存
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value) {
 boolean result = false;
 try {
 ValueOperationsSerializable, Object> operations = redisTemplate.opsForValue();
 operations.set(key, value);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 * 寫入緩存設(shè)置時效時間
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
 boolean result = false;
 try {
 ValueOperationsSerializable, Object> operations = redisTemplate.opsForValue();
 operations.set(key, value);
 redisTemplate.expire(key, expireTime, timeUnit);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 * 批量刪除對應(yīng)的value
 * @param keys
 */
 public void remove(final String... keys) {
 for (String key : keys) {
 remove(key);
 }
 }
 /**
 * 批量刪除key
 * @param pattern
 */
 public void removePattern(final String pattern) {
 SetSerializable> keys = redisTemplate.keys(pattern);
 if (keys.size() > 0){
 redisTemplate.delete(keys);
 }
 }
 /**
 * 刪除對應(yīng)的value
 * @param key
 */
 public void remove(final String key) {
 if (exists(key)) {
 redisTemplate.delete(key);
 }
 }
 /**
 * 判斷緩存中是否有對應(yīng)的value
 * @param key
 * @return
 */
 public boolean exists(final String key) {
 return redisTemplate.hasKey(key);
 }
 /**
 * 讀取緩存
 * @param key
 * @return
 */
 public Object get(final String key) {
 Object result = null;
 ValueOperationsSerializable, Object> operations = redisTemplate.opsForValue();
 result = operations.get(key);
 return result;
 }
 /**
 * 哈希 添加
 * @param key
 * @param hashKey
 * @param value
 */
 public void hmSet(String key, Object hashKey, Object value){
 HashOperationsString, Object, Object> hash = redisTemplate.opsForHash();
 hash.put(key,hashKey,value);
 }
 /**
 * 哈希獲取數(shù)據(jù)
 * @param key
 * @param hashKey
 * @return
 */
 public Object hmGet(String key, Object hashKey){
 HashOperationsString, Object, Object> hash = redisTemplate.opsForHash();
 return hash.get(key,hashKey);
 }
 /**
 * 列表添加
 * @param k
 * @param v
 */
 public void lPush(String k,Object v){
 ListOperationsString, Object> list = redisTemplate.opsForList();
 list.rightPush(k,v);
 }
 /**
 * 列表獲取
 * @param k
 * @param l
 * @param l1
 * @return
 */
 public ListObject> lRange(String k, long l, long l1){
 ListOperationsString, Object> list = redisTemplate.opsForList();
 return list.range(k,l,l1);
 }
 /**
 * 集合添加
 * @param key
 * @param value
 */
 public void add(String key,Object value){
 SetOperationsString, Object> set = redisTemplate.opsForSet();
 set.add(key,value);
 }
 /**
 * 集合獲取
 * @param key
 * @return
 */
 public SetObject> setMembers(String key){
 SetOperationsString, Object> set = redisTemplate.opsForSet();
 return set.members(key);
 }
 /**
 * 有序集合添加
 * @param key
 * @param value
 * @param scoure
 */
 public void zAdd(String key,Object value,double scoure){
 ZSetOperationsString, Object> zset = redisTemplate.opsForZSet();
 zset.add(key,value,scoure);
 }
 /**
 * 有序集合獲取
 * @param key
 * @param scoure
 * @param scoure1
 * @return
 */
 public SetObject> rangeByScore(String key,double scoure,double scoure1){
 ZSetOperationsString, Object> zset = redisTemplate.opsForZSet();
 return zset.rangeByScore(key, scoure, scoure1);
 }

5、測試,修改controller

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chenqi.springboot.redis.RedisUtils;
import com.chenqi.springboot.service.TestService;
@RestController
public class SpringBootController {
 
 public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
 
 @Autowired
 TestService testService;
 
 @Autowired
 private RedisUtils redisUtils;
 @RequestMapping(value = "/hello/{id}")
 public String hello(@PathVariable(value = "id") String id){
 //查詢緩存中是否存在
 boolean hasKey = redisUtils.exists(id);
 String str = "";
 if(hasKey){
 //獲取緩存
 Object object = redisUtils.get(id);
 log.info("從緩存獲取的數(shù)據(jù)"+ object);
 str = object.toString();
 }else{
 //從數(shù)據(jù)庫中獲取信息
 log.info("從數(shù)據(jù)庫中獲取數(shù)據(jù)");
 str = testService.test();
 //數(shù)據(jù)插入緩存(set中的參數(shù)含義:key值,user對象,緩存存在時間10(long類型),時間單位)
 redisUtils.set(id,str,10L,TimeUnit.MINUTES);
 log.info("數(shù)據(jù)插入緩存" + str);
 }
 return str;
 }
}

啟動項(xiàng)目,第一次訪問:http://localhost:8002/hello/111


通過控制臺輸出,我們可以看到是從數(shù)據(jù)庫中獲取的數(shù)據(jù),并且存入了redis緩存中。

我們再次刷新瀏覽器

可以看到,第二次是從緩存中讀取的,我們試試不斷刷新瀏覽器

可以看到,之后都是從緩存中獲取的。

到此我們的redis就配置好了。

SpringBoot集成Redis-demo下載

急需demo的兄弟就自行下載吧,不急可以留言郵箱,一般48小時內(nèi)會發(fā)。

到此這篇關(guān)于使用SpringBoot集成redis的方法的文章就介紹到這了,更多相關(guān)SpringBoot集成redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • 關(guān)于Springboot2.x集成lettuce連接redis集群報(bào)超時異常Command timed out after 6 second(s)
  • SpringBoot集成Redis實(shí)現(xiàn)消息隊(duì)列的方法
  • springboot集成redis實(shí)現(xiàn)簡單秒殺系統(tǒng)
  • SpringBoot集成Redisson實(shí)現(xiàn)分布式鎖的方法示例
  • springBoot集成redis的key,value序列化的相關(guān)問題
  • SpringBoot集成Redis的實(shí)現(xiàn)示例
  • springboot集成測試?yán)锏膔edis
  • SpringBoot集成Redis的思路詳解

標(biāo)簽:仙桃 湘潭 衡水 銅川 崇左 蘭州 黃山 湖南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《使用SpringBoot集成redis的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    二手房| 罗平县| 讷河市| 大理市| 湘阴县| 图木舒克市| 黄平县| 古蔺县| 防城港市| 黄龙县| 浦城县| 秀山| 乐安县| 南投市| 萝北县| 射洪县| 海淀区| 崇明县| 英山县| 平武县| 永川市| 霍邱县| 禹州市| 灵宝市| 拜泉县| 柳林县| 张家口市| 高淳县| 祁连县| 迭部县| 芦溪县| 乌拉特前旗| 长汀县| 唐山市| 宜丰县| 荃湾区| 鹿邑县| 秦皇岛市| 金堂县| 渭源县| 文化|