前言

在实际的开发中,会有这样的场景。有一个微服务需要提供一个查询的服务,但是需要查询的数据库表的数据量十分庞大,查询所需要的时间很长。

此时就可以考虑在项目中加入缓存。

引入依赖

在maven项目中引入如下依赖。并且需要在本地安装redis。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>

配置redis

在SpringBoot的配置文件中添加如下代码。

redis:
host: 127.0.0.1
port: 6379
timeout: 5000
database: 0
jedis:
pool:
max-idle: 8
max-wait:
min-idle: 0

添加redis配置文件

新建名为RedisConfig的配置类。

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
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 java.time.Duration; /**
* RedisConfig
*
* @author detectiveHLH
* @date 2018-10-11 14:39
**/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, 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 RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//redis序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
jackson2JsonRedisSerializer.setObjectMapper(om); StringRedisTemplate template = new StringRedisTemplate(factory);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
} /**
* 自定义CacheManager
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
//全局redis缓存过期时间
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
}

添加缓存配置

在项目的service层中的实现类中,添加@Cacheable注解。

import java.util.HashMap;

/**
* UserLoginServiceImpl
*
* @author detectiveHLH
* @date 2018-10-10 17:20
**/
@Service
public class UserLoginServiceImpl implements UserLoginService {
@Autowired
private UserLoginMapper userLoginMapper; @Override
@Cacheable(value = "usercache")
public HashMap getByUserName(String userName) {
System.out.println("此时没有走缓存");
return userLoginMapper.getByUserName(userName);
}
}

然后调用一次该接口。就可以在redis中看到如下的key。

"usercache::com.detectiveHLH.api.service.impl.UserLoginServiceImplgetByUserNameSolarFarm"

同时,可以在控制台中看到有"此时没有走缓存"的输出。然后再次调用该接口,就可以看到返回的速度明显变快,并且没有"此时没有走缓存"输出。说明

此时的接口走的是缓存。

博客: 个人博客地址

在SpringBoot中添加Redis的更多相关文章

  1. 由浅入深学习springboot中使用redis

    很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...

  2. (一)由浅入深学习springboot中使用redis

    很多时候,我们会在springboot中配置redis,但是就那么几个配置就配好了,没办法知道为什么,这里就详细的讲解一下 这里假设已经成功创建了一个springboot项目. redis连接工厂类 ...

  3. SpringBoot中使用Redis

    在SpringBoot中使用Redis,思路如下: 查询时先查Redis缓存,如果缓存中存在信息,就直接从缓存中获取. 如果缓存中没有相关信息,就去数据库中查找,查完顺便将信息存放进缓存里,以便下一次 ...

  4. SpringBoot 中使用redis以及redisTemplate

    1.首先在pom.xml中添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <art ...

  5. 在springboot中使用redis缓存,将缓存序列化为json格式的数据

    背景 在springboot中使用redis缓存结合spring缓存注解,当缓存成功后使用gui界面查看redis中的数据 原因 springboot缓存默认的序列化是jdk提供的 Serializa ...

  6. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  7. 你知道如何在springboot中使用redis吗

    特别说明:本文针对的是新版 spring boot 2.1.3,其 spring data 依赖为 spring-boot-starter-data-redis,且其默认连接池为 lettuce ​  ...

  8. SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存

    1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...

  9. 在SpringBoot中引入Redis

    前言 之前我们只是在Spring中加入Redis用于session的存放,并没有对redis进行主动的存放,这次我们需要加入redis工具类来方便我们在实际使用过程中操作redis 已经加入我的git ...

随机推荐

  1. nginx高级用法汇总

    1,nginx限制IP访问,允许IP访问 1.1 模块:nginx_http_access_module 注意:检测顺序是按配置顺序进行的,匹配首条规则将会被使用,所以要注意在配置文件配置的顺序. a ...

  2. (PMP)解题技巧和典型题目分析(每日20题)

    3.11 1.A(C),2.D,3.A,4.B,5.A(C),6.D(A),7.D,8.A(D),9.B,10.D(B), 11.C(B),12.C(D),13.B,14.D,15.C,16.C(D) ...

  3. cURL error 60: SSL certificate problem...

    php在curl的时候报错 cURL error 60: SSL certificate problem: unable to get local issuer certificate (see ht ...

  4. 10.1牛客J题

    https://www.nowcoder.com/acm/contest/201/J Description: 给你一行括号,定义了括号合格的形式,然后Q次询问,问你这个区间内括号是否合格 Solut ...

  5. 2018年1月20日上海MVP线下技术分享会纪实

    1月20日正值大寒节气,在微软MVP朱兴亮的组织牵头下,上海MVP自发举办了题为<跟社区专家一起聊聊混合云.领域驱动.区块链和数字营销>的技术交流会.四名来自上海的MVP分别在自己擅长的技 ...

  6. 基于HTTP的长轮询简单实现

    Web客户端与服务器之间基于Ajax(http)的常用通信方式,分为短连接与长轮询. 短连接:客户端和服务器每进行一次HTTP操作,就建立一次连接,任务结束就中断连接. 在长轮询机制中,客户端像传统轮 ...

  7. Android JNI 学习(五):References Api

    1. NewGlobalRef(创建全局引用) jobjectNewGlobalRef(JNIEnv *env, jobject obj); 创建 obj 参数所引用对象的新全局引用.obj 参数既可 ...

  8. 吴恩达机器学习笔记40-用调和平均数F来进行查准率和查全率之间的权衡(Trading Off Precision and Recall by F sore)

    在很多应用中,我们希望能够保证查准率和查全率的相对平衡. 我们可以将不同阀值情况下,查全率与查准率的关系绘制成图表,曲线的形状根据数据的不同而不同: 我们希望有一个帮助我们选择这个阀值的方法.一种方法 ...

  9. IntelliJ IDEA 常用快捷键使用说明

    Ctrl + / 可以实现单行注释的快速添加和取消.xml和html注释也能操作. Ctrl + Y 删除选中的代码,或者光标所在行,同时删除代码所占的空间. Ctrl + Alt + V 快速抽取变 ...

  10. 一句话的事儿,Head first 设计模式

    head first 设计模式,是比较有趣的一本设计模式的书. 在学校里看书和在工作时看书,意义是不一样的.在学校时是为读书而读书,我们可以从0到1,我们有的是时间.但是工作后就不一样. 我觉得这时的 ...