springboot集成redis的方法

springboot集成redis的方法

今天小编给大家分享一下springboot集成redis的方法的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

1. pom.xml添加依赖

springboot集成redis的方法

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--集成redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies>

2. application-dev.xml配置

#单机模式spring:redis:host:192.168.56.101#Redis服务器地址database:0#Redis数据库索引(默认为0)port:6379#Redis服务器连接端口password:redis#Redis服务器连接密码(默认为空)timeout:300ms#连接超时时间(毫秒)

# 哨兵模式

spring:redis:sentinel:master:mymasternodes:192.168.56.101:26379,192.168.56.102:26379,192.168.56.103:26379password:redis

3. java config配置(单节点)

packagecom.powertrade.redis.common.config;importcom.fasterxml.jackson.annotation.JsonAutoDetect;importcom.fasterxml.jackson.annotation.PropertyAccessor;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;importorg.springframework.cache.annotation.EnableCaching;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.cache.RedisCacheConfiguration;importorg.springframework.data.redis.cache.RedisCacheManager;importorg.springframework.data.redis.cache.RedisCacheWriter;importorg.springframework.data.redis.connection.RedisConnectionFactory;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;importorg.springframework.data.redis.serializer.RedisSerializationContext;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.StringRedisSerializer;importjava.time.Duration;/***Redis单机配置*/@EnableCaching@ConfigurationpublicclassBaseRedisConfig{@BeanpublicRedisTemplate<String,Object>redisTemplate(RedisConnectionFactoryredisConnectionFactory){RedisSerializer<Object>serializer=redisSerializer();RedisTemplate<String,Object>redisTemplate=newRedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(newStringRedisSerializer());redisTemplate.setValueSerializer(serializer);redisTemplate.setHashKeySerializer(newStringRedisSerializer());redisTemplate.setHashValueSerializer(serializer);redisTemplate.afterPropertiesSet();returnredisTemplate;}@BeanpublicRedisSerializer<Object>redisSerializer(){//创建JSON序列化器Jackson2JsonRedisSerializer<Object>serializer=newJackson2JsonRedisSerializer<>(Object.class);ObjectMapperobjectMapper=newObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);//必须设置,否则无法将JSON转化为对象,会转化成Map类型objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);serializer.setObjectMapper(objectMapper);returnserializer;}@BeanpublicRedisCacheManagerredisCacheManager(RedisConnectionFactoryredisConnectionFactory){RedisCacheWriterredisCacheWriter=RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);//设置Redis缓存有效期为1天RedisCacheConfigurationredisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));returnnewRedisCacheManager(redisCacheWriter,redisCacheConfiguration);}}

4. 哨兵机制 (多节点配置)

packagecom.powertrade.redis.common.config;importcom.fasterxml.jackson.annotation.JsonAutoDetect;importcom.fasterxml.jackson.annotation.PropertyAccessor;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.cache.annotation.EnableCaching;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.cache.RedisCacheConfiguration;importorg.springframework.data.redis.cache.RedisCacheManager;importorg.springframework.data.redis.cache.RedisCacheWriter;importorg.springframework.data.redis.connection.RedisConnectionFactory;importorg.springframework.data.redis.connection.RedisNode;importorg.springframework.data.redis.connection.RedisPassword;importorg.springframework.data.redis.connection.RedisSentinelConfiguration;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;importorg.springframework.data.redis.serializer.RedisSerializationContext;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.StringRedisSerializer;importjava.time.Duration;/***Redis哨兵机制配置*/@EnableCaching@ConfigurationpublicclassBaseRedisConfig{@Value("${spring.redis.sentinel.nodes}")privateStringredisNodes;@Value("${spring.redis.sentinel.master}")privateStringmaster;@Value("${spring.redis.sentinel.password}")privateStringpassword;/***redis哨兵配置*/@BeanpublicRedisSentinelConfigurationredisSentinelConfiguration(){RedisSentinelConfigurationconfiguration=newRedisSentinelConfiguration();String[]host=redisNodes.split(",");for(StringredisHost:host){String[]item=redisHost.split(":");Stringip=item[0];Stringport=item[1];configuration.addSentinel(newRedisNode(ip,Integer.parseInt(port)));}configuration.setPassword(RedisPassword.of(password));configuration.setMaster(master);returnconfiguration;}@BeanpublicRedisTemplate<String,Object>redisTemplate(RedisConnectionFactoryredisConnectionFactory){RedisSerializer<Object>serializer=redisSerializer();RedisTemplate<String,Object>redisTemplate=newRedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(newStringRedisSerializer());redisTemplate.setValueSerializer(serializer);redisTemplate.setHashKeySerializer(newStringRedisSerializer());redisTemplate.setHashValueSerializer(serializer);redisTemplate.afterPropertiesSet();returnredisTemplate;}@BeanpublicRedisSerializer<Object>redisSerializer(){//创建JSON序列化器Jackson2JsonRedisSerializer<Object>serializer=newJackson2JsonRedisSerializer<>(Object.class);ObjectMapperobjectMapper=newObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);//必须设置,否则无法将JSON转化为对象,会转化成Map类型objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);serializer.setObjectMapper(objectMapper);returnserializer;}@BeanpublicRedisCacheManagerredisCacheManager(RedisConnectionFactoryredisConnectionFactory){RedisCacheWriterredisCacheWriter=RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);//设置Redis缓存有效期为1天RedisCacheConfigurationredisCacheConfiguration=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));returnnewRedisCacheManager(redisCacheWriter,redisCacheConfiguration);}}

5. redis工具类

packagecom.powertrade.redis.common.utils;importlombok.RequiredArgsConstructor;importorg.springframework.data.redis.core.BoundSetOperations;importorg.springframework.data.redis.core.HashOperations;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.stereotype.Component;importjava.util.Collection;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.Set;importjava.util.concurrent.TimeUnit;@Component@RequiredArgsConstructorpublicclassRedisCache{publicfinalRedisTemplateredisTemplate;/***缓存基本的对象,Integer、String、实体类等**@paramkey缓存的键值*@paramvalue缓存的值*/public<T>voidsetCacheObject(finalStringkey,finalTvalue){redisTemplate.opsForValue().set(key,value);}/***缓存基本的对象,Integer、String、实体类等**@paramkey缓存的键值*@paramvalue缓存的值*@paramtimeout时间*@paramtimeUnit时间颗粒度*/public<T>voidsetCacheObject(finalStringkey,finalTvalue,finalIntegertimeout,finalTimeUnittimeUnit){redisTemplate.opsForValue().set(key,value,timeout,timeUnit);}/***设置有效时间**@paramkeyRedis键*@paramtimeout超时时间*@returntrue=设置成功;false=设置失败*/publicbooleanexpire(finalStringkey,finallongtimeout){returnexpire(key,timeout,TimeUnit.SECONDS);}/***设置有效时间**@paramkeyRedis键*@paramtimeout超时时间*@paramunit时间单位*@returntrue=设置成功;false=设置失败*/publicbooleanexpire(finalStringkey,finallongtimeout,finalTimeUnitunit){returnredisTemplate.expire(key,timeout,unit);}/***获得缓存的基本对象。**@paramkey缓存键值*@return缓存键值对应的数据*/public<T>TgetCacheObject(finalStringkey){ValueOperations<String,T>operation=redisTemplate.opsForValue();returnoperation.get(key);}/***删除单个对象**@paramkey*/publicbooleandeleteObject(finalStringkey){returnredisTemplate.delete(key);}/***删除集合对象**@paramcollection多个对象*@return*/publiclongdeleteObject(finalCollectioncollection){returnredisTemplate.delete(collection);}/***缓存List数据**@paramkey缓存的键值*@paramdataList待缓存的List数据*@return缓存的对象*/public<T>longsetCacheList(finalStringkey,finalList<T>dataList){Longcount=redisTemplate.opsForList().rightPushAll(key,dataList);returncount==null?0:count;}/***获得缓存的list对象**@paramkey缓存的键值*@return缓存键值对应的数据*/public<T>List<T>getCacheList(finalStringkey){returnredisTemplate.opsForList().range(key,0,-1);}/***缓存Set**@paramkey缓存键值*@paramdataSet缓存的数据*@return缓存数据的对象*/public<T>BoundSetOperations<String,T>setCacheSet(finalStringkey,finalSet<T>dataSet){BoundSetOperations<String,T>setOperation=redisTemplate.boundSetOps(key);Iterator<T>it=dataSet.iterator();while(it.hasNext()){setOperation.add(it.next());}returnsetOperation;}/***获得缓存的set**@paramkey*@return*/public<T>Set<T>getCacheSet(finalStringkey){returnredisTemplate.opsForSet().members(key);}/***缓存Map**@paramkey*@paramdataMap*/public<T>voidsetCacheMap(finalStringkey,finalMap<String,T>dataMap){if(dataMap!=null){redisTemplate.opsForHash().putAll(key,dataMap);}}/***获得缓存的Map**@paramkey*@return*/public<T>Map<String,T>getCacheMap(finalStringkey){returnredisTemplate.opsForHash().entries(key);}/***往Hash中存入数据**@paramkeyRedis键*@paramhKeyHash键*@paramvalue值*/public<T>voidsetCacheMapValue(finalStringkey,finalStringhKey,finalTvalue){redisTemplate.opsForHash().put(key,hKey,value);}/***获取Hash中的数据**@paramkeyRedis键*@paramhKeyHash键*@returnHash中的对象*/public<T>TgetCacheMapValue(finalStringkey,finalStringhKey){HashOperations<String,String,T>opsForHash=redisTemplate.opsForHash();returnopsForHash.get(key,hKey);}/***获取多个Hash中的数据**@paramkeyRedis键*@paramhKeysHash键集合*@returnHash对象集合*/public<T>List<T>getMultiCacheMapValue(finalStringkey,finalCollection<Object>hKeys){returnredisTemplate.opsForHash().multiGet(key,hKeys);}/***获得缓存的基本对象列表**@parampattern字符串前缀*@return对象列表*/publicCollection<String>keys(finalStringpattern){returnredisTemplate.keys(pattern);}}

以上就是“springboot集成redis的方法”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注恰卡编程网行业资讯频道。

发布于 2022-03-29 22:27:47
收藏
分享
海报
0 条评论
26
上一篇:基于springboot+bootstrap+mysql+redis怎么搭建完整的权限架构 下一篇:Sparse R-CNN实例分析
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码