前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache、RedisCache、ConcurrentMapCache等。

这一节我们来看看Spring Cache使用RedisCache。

一、RedisCache使用演示

Redis是一个key-value存储系统,在web应用上被广泛应用,这里就不对其过多描述了。

本章节示例是在Spring Boot集成Spring Cache的源码基础上进行改造。源码地址:https://github.com/imyanger/springboot-project/tree/master/p20-springboot-cache

使用RedisCache作为缓存,我们先引入相关依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

然后SpringBoot配置文件中,对redis进行配置。

server:
port: 10900 spring:
profiles:
active: dev
redis:
host: localhost #redis服务器地址
port: 6379 #redis端口
password: 1234 #redis密码
timeout: 60000 #连接超时时间
database: 0 #数据库索引,默认为0

SpringBoot中使用Redis,可以通过Spring Cache的注解,也可以使用RedisTemplate来实现,大部分情况下,因为注解存在一定局限性不够灵活,一般实际开发中都是使用的RedisTemplate。

附上CacheConfig注入RedisTemplate,如果不需要使用RedisTemplate,直接将@EnableCaching注解加在SpringBoot启动类上即可。

@Configuration
@EnableCaching
public class CacheConfig { @Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory); // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper); redisTemplate.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
} }

这样就可以开始使用RedisCache了,测试代码与Spring Boot集成Spring Cache一致。

CacheApi接口调用类,方便调用进行测试。

@RestController
@RequestMapping("cache")
public class CacheApi { @Autowired
private CacheService cacheService; @GetMapping("get")
public User get(@RequestParam int id){
return cacheService.get(id);
} @PostMapping("set")
public User set(@RequestParam int id, @RequestParam String code, @RequestParam String name){
User u = new User(code, name);
return cacheService.set(id, u);
} @DeleteMapping("del")
public void del(@RequestParam int id){
cacheService.del(id);
} }

CacheService缓存业务处理类,添加缓存,更新缓存和删除。

@Slf4j
@Service
public class CacheService { private Map<Integer, User> dataMap = new HashMap <Integer, User>(){
{
for (int i = 1; i < 100 ; i++) {
User u = new User("code" + i, "name" + i);
put(i, u);
}
}
}; // 获取数据
@Cacheable(value = "cache", key = "'user:' + #id")
public User get(int id){
log.info("通过id{}查询获取", id);
return dataMap.get(id);
} // 更新数据
@CachePut(value = "cache", key = "'user:' + #id")
public User set(int id, User u){
log.info("更新id{}数据", id);
dataMap.put(id, u);
return u;
} //删除数据
@CacheEvict(value = "cache", key = "'user:' + #id")
public void del(int id){
log.info("删除id{}数据", id);
dataMap.remove(id);
} }

启动服务进行测试,可以看到缓存功能正常,且打开redis进行查看,也能看到对应的缓存数据。

源码地址:https://github.com/imyanger/springboot-project/tree/master/p21-springboot-cache-redis

SpringBoot系列:Spring Boot集成Spring Cache,使用RedisCache的更多相关文章

  1. SpringBoot系列:Spring Boot集成Spring Cache,使用EhCache

    前面的章节,讲解了Spring Boot集成Spring Cache,Spring Cache已经完成了多种Cache的实现,包括EhCache.RedisCache.ConcurrentMapCac ...

  2. Spring Boot集成Spring Data Reids和Spring Session实现Session共享

    首先,需要先集成Redis的支持,参考:http://www.cnblogs.com/EasonJim/p/7805665.html Spring Boot集成Spring Data Redis+Sp ...

  3. Spring boot集成spring session实现session共享

    最近使用spring boot开发一个系统,nginx做负载均衡分发请求到多个tomcat,此时访问页面会把请求分发到不同的服务器,session是存在服务器端,如果首次访问被分发到A服务器,那么se ...

  4. Spring Boot 集成spring security4

    项目GitHub地址 : https://github.com/FrameReserve/TrainingBoot Spring Boot (三)集成spring security,标记地址: htt ...

  5. Spring Boot 集成 Spring Security 实现权限认证模块

    作者:王帅@CodeSheep   写在前面 关于 Spring Security Web系统的认证和权限模块也算是一个系统的基础设施了,几乎任何的互联网服务都会涉及到这方面的要求.在Java EE领 ...

  6. Spring boot 集成Spring Security

    依赖jar <dependency> <groupId>org.springframework.cloud</groupId> <artifactId> ...

  7. SpringBoot系列:Spring Boot集成Spring Cache

    一.关于Spring Cache 缓存在现在的应用中越来越重要, Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework. ...

  8. Spring Boot 集成 Spring Security

    1.添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  9. Spring Boot 集成 Spring Security 入门案例教程

    前言 本文作为入门级的DEMO,完全按照官网实例演示: 项目目录结构 Maven 依赖 <parent> <groupId>org.springframework.boot&l ...

随机推荐

  1. solr java代码

    添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...

  2. nfs 存储服务

    今日内容: NFS 1.什么是nfs? network file system 网络文件系统 nfs共享存储 2.nfs能干什么? nfs 能为 不同主机系统之间 实现 文件的共享 3.为什么要使用n ...

  3. Spark学习之RDDs介绍

    什么是RDDS? RDDS即Resilient distributed datasets(弹性分布式数据集). Spark中,所有计算都是通过RDDs的创建,转换,操作完成的. 一个RDD是一个不可改 ...

  4. MongoDB的查询索引

    ​ 目录 为什么要建立索引? 索引的分类有哪些? _id索引 单键索引 多键索引 复合索引 过期索引 hello,今天是万圣节

  5. .NET进阶篇-丑话先说,Flag先立--致青春

    作为开发者,工作了半年,也总觉得技术栈和刚毕业区别不大,用的技术还都是N年前的,每每看到新东西,也只心里哇塞惊叹一下,然后就回归于忙碌.怪自己的技术池太浅,热门的令人称奇的技术也都是在其他巨人的肩膀上 ...

  6. python openpyxl内存不主动释放 ——关闭Excel工作簿后内存依旧(MemoryError)

    在openpyxl对Excel读写操作过程中,发现内存没有马上释放,如果得多次读取大文件,内存爪机,后续代码就无法运行. 尝试:各种wb.save()或者with open等途径无法解决. 发现:因为 ...

  7. MySQL 深入理解索引B+树存储 (转载))

    出处:http://blog.codinglabs.org/articles/theory-of-mysql-index.html   摘要 本文以MySQL数据库为研究对象,讨论与数据库索引相关的一 ...

  8. kotlin系列文章 --- 3.条件控制

    if表达式 一个if语句包含一个布尔表达式和一条或多条语句 // 基础用法 var max = a if (a<b) max = b // 加上else var max: Int if(a> ...

  9. kotlin -- 可见性修饰符

    puiblic Kotlin的可见修饰符与Java类似,但是默认可见性不同,Java默认包私有,kotlin默认public ### internal internal 只在模块内部可见.一个模块就是 ...

  10. Java基础学习笔记(五) - 常用的API

    API介绍 概念:API 即应用编程程序接口.Java API是JDK中提供给我们使用的类说明文档,这些类将底层的代码实现封装.无需关心这些类是如何实现,只需要学习如何使用. 使用:通过API找到需要 ...