使用SpringBoot集成redis的方法
今天,日月在这里教大家如何使用springBoot集成redis,说实话比较简单,网上也有大把的教程。先套用一下网上的简介。
定义
REmoteDIctionaryServer(Redis)是一个由SalvatoreSanfilippo写的key-value存储系统。
Redis是一个开源的使用ANSIC语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是字符串(String),哈希(Map),列表(list),集合(sets)和有序集合(sortedsets)等类型。
reids的优点
以下是Redis的一些优点。
异常快-Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。
支持丰富的数据类型-Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。
操作具有原子性-所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值。
多实用工具-Redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等。
Redis安装
Window下安装
下载地址:https://github.com/MSOpenTech/redis/releases。
Redis支持32位和64位。这个需要根据你系统平台的实际情况选择,这里我们下载Redis-x64-xxx.zip压缩包到C盘,解压后,将文件夹重新命名为redis。
打开一个cmd窗口使用cd命令切换目录到C:\redis
运行redis-server.exeredis.windows.conf
如果想方便的话,可以把redis的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个redis.windows.conf可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:
集成redis
我们还是延用上一章的项目:Springboot集成springcloud-config实现dataSource热部署
1、添加依赖
org.springframework.boot spring-boot-starter-redis 1.4.1.RELEASE com.alibaba fastjson 1.2.3 com.fasterxml.jackson.core jackson-databind
2、在配置中心里添加redis配置
spring.redis.host=127.0.0.1 #Redis服务器连接端口 spring.redis.port=6379 #Redis服务器连接密码(默认为空) spring.redis.password= #连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 #连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 #连接池中的最大空闲连接 spring.redis.pool.max-idle=8 #连接池中的最小空闲连接 spring.redis.pool.min-idle=0 #连接超时时间(毫秒) spring.redis.timeout=30000
3、配置类RedisConfig
importjava.lang.reflect.Method;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.cache.CacheManager;
importorg.springframework.cache.annotation.CachingConfigurerSupport;
importorg.springframework.cache.annotation.EnableCaching;
importorg.springframework.cache.interceptor.KeyGenerator;
importorg.springframework.cloud.context.config.annotation.RefreshScope;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.data.redis.cache.RedisCacheManager;
importorg.springframework.data.redis.connection.RedisConnectionFactory;
importorg.springframework.data.redis.connection.jedis.JedisConnectionFactory;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.data.redis.core.StringRedisTemplate;
importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
importcom.fasterxml.jackson.annotation.PropertyAccessor;
importcom.fasterxml.jackson.annotation.JsonAutoDetect;
importcom.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
publicclassRedisConfigextendsCachingConfigurerSupport{
@Value("${spring.redis.host}")
privateStringhost;
@Value("${spring.redis.port}")
privateintport;
@Value("${spring.redis.timeout}")
privateinttimeout;
@Value("${spring.redis.password}")
privateStringpassword;
@Value("${spring.redis.pool.max-active}")
privateintmaxActive;
@Value("${spring.redis.pool.max-wait}")
privateintmaxWait;
@Value("${spring.redis.pool.max-idle}")
privateintmaxIdle;
@Value("${spring.redis.pool.min-idle}")
privateintminIdle;
@RefreshScope
@Bean
publicKeyGeneratorwiselyKeyGenerator(){
returnnewKeyGenerator(){
@Override
publicObjectgenerate(Objecttarget,Methodmethod,Object...params){
StringBuildersb=newStringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for(Objectobj:params){
sb.append(obj.toString());
}
returnsb.toString();
}
};
}
@RefreshScope
@Bean
publicJedisConnectionFactoryredisConnectionFactory(){
JedisConnectionFactoryfactory=newJedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout);//设置连接超时时间
factory.setPassword(password);
factory.getPoolConfig().setMaxIdle(maxIdle);
factory.getPoolConfig().setMinIdle(minIdle);
factory.getPoolConfig().setMaxTotal(maxActive);
factory.getPoolConfig().setMaxWaitMillis(maxWait);
returnfactory;
}
@RefreshScope
@Bean
publicCacheManagercacheManager(RedisTemplateredisTemplate){
RedisCacheManagercacheManager=newRedisCacheManager(redisTemplate);
//Numberofsecondsbeforeexpiration.Defaultstounlimited(0)
cacheManager.setDefaultExpiration(10);//设置key-value超时时间
returncacheManager;
}
@RefreshScope
@Bean
publicRedisTemplateredisTemplate(RedisConnectionFactoryfactory){
StringRedisTemplatetemplate=newStringRedisTemplate(factory);
setSerializer(template);//设置序列化工具,这样ReportBean不需要实现Serializable接口
template.afterPropertiesSet();
returntemplate;
}
@RefreshScope
privatevoidsetSerializer(StringRedisTemplatetemplate){
Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class);
ObjectMapperom=newObjectMapper();
om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
4、RedisUtils类
importjava.io.Serializable;
importjava.util.List;
importjava.util.Set;
importjava.util.concurrent.TimeUnit;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.redis.core.HashOperations;
importorg.springframework.data.redis.core.ListOperations;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.data.redis.core.SetOperations;
importorg.springframework.data.redis.core.ValueOperations;
importorg.springframework.data.redis.core.ZSetOperations;
importorg.springframework.stereotype.Service;
@Service
publicclassRedisUtils{
@Autowired
privateRedisTemplateredisTemplate;
/**
*写入缓存
*@paramkey
*@paramvalue
*@return
*/
publicbooleanset(finalStringkey,Objectvalue){
booleanresult=false;
try{
ValueOperationsoperations=redisTemplate.opsForValue();
operations.set(key,value);
result=true;
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
/**
*写入缓存设置时效时间
*@paramkey
*@paramvalue
*@return
*/
publicbooleanset(finalStringkey,Objectvalue,LongexpireTime,TimeUnittimeUnit){
booleanresult=false;
try{
ValueOperationsoperations=redisTemplate.opsForValue();
operations.set(key,value);
redisTemplate.expire(key,expireTime,timeUnit);
result=true;
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
/**
*批量删除对应的value
*@paramkeys
*/
publicvoidremove(finalString...keys){
for(Stringkey:keys){
remove(key);
}
}
/**
*批量删除key
*@parampattern
*/
publicvoidremovePattern(finalStringpattern){
Setkeys=redisTemplate.keys(pattern);
if(keys.size()>0){
redisTemplate.delete(keys);
}
}
/**
*删除对应的value
*@paramkey
*/
publicvoidremove(finalStringkey){
if(exists(key)){
redisTemplate.delete(key);
}
}
/**
*判断缓存中是否有对应的value
*@paramkey
*@return
*/
publicbooleanexists(finalStringkey){
returnredisTemplate.hasKey(key);
}
/**
*读取缓存
*@paramkey
*@return
*/
publicObjectget(finalStringkey){
Objectresult=null;
ValueOperationsoperations=redisTemplate.opsForValue();
result=operations.get(key);
returnresult;
}
/**
*哈希添加
*@paramkey
*@paramhashKey
*@paramvalue
*/
publicvoidhmSet(Stringkey,ObjecthashKey,Objectvalue){
HashOperationshash=redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
*哈希获取数据
*@paramkey
*@paramhashKey
*@return
*/
publicObjecthmGet(Stringkey,ObjecthashKey){
HashOperationshash=redisTemplate.opsForHash();
returnhash.get(key,hashKey);
}
/**
*列表添加
*@paramk
*@paramv
*/
publicvoidlPush(Stringk,Objectv){
ListOperationslist=redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
*列表获取
*@paramk
*@paraml
*@paraml1
*@return
*/
publicList
5、测试,修改controller
importjava.util.concurrent.TimeUnit;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
importcom.chenqi.springboot.redis.RedisUtils;
importcom.chenqi.springboot.service.TestService;
@RestController
publicclassSpringBootController{
publicstaticfinalLoggerlog=LoggerFactory.getLogger(SpringBootController.class);
@Autowired
TestServicetestService;
@Autowired
privateRedisUtilsredisUtils;
@RequestMapping(value="/hello/{id}")
publicStringhello(@PathVariable(value="id")Stringid){
//查询缓存中是否存在
booleanhasKey=redisUtils.exists(id);
Stringstr="";
if(hasKey){
//获取缓存
Objectobject=redisUtils.get(id);
log.info("从缓存获取的数据"+object);
str=object.toString();
}else{
//从数据库中获取信息
log.info("从数据库中获取数据");
str=testService.test();
//数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
redisUtils.set(id,str,10L,TimeUnit.MINUTES);
log.info("数据插入缓存"+str);
}
returnstr;
}
}
启动项目,第一次访问:http://localhost:8002/hello/111
通过控制台输出,我们可以看到是从数据库中获取的数据,并且存入了redis缓存中。
我们再次刷新浏览器
可以看到,第二次是从缓存中读取的,我们试试不断刷新浏览器
可以看到,之后都是从缓存中获取的。
到此我们的redis就配置好了。
SpringBoot集成Redis-demo下载
急需demo的兄弟就自行下载吧,不急可以留言邮箱,一般48小时内会发。
到此这篇关于使用SpringBoot集成redis的方法的文章就介绍到这了,更多相关SpringBoot集成redis内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。