前言

之前已经写过一篇文章介绍SpringBoot整合Spring Cache,SpringBoot默认使用的是ConcurrentMapCacheManager,在实际项目中,我们需要一个高可用的、分布式的缓存解决方案,使用默认的这种缓存方式,只是在当前进程里缓存了而已。Spring Cache整合Redis来实现缓存,其实也不是一件复杂的事情,下面就开始吧。

关于Spring Cache的运用,请参考[快学SpringBoot]快速上手好用方便的Spring Cache缓存框架

新建一个SpringBoot项目

依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>

主要是最下面两个依赖:spring-boot-starter-cache 和 spring-boot-starter-data-redis。

配置Redis

在application.properties中添加redis的配置

spring.redis.host=127.0.0.1
# spring.redis.password=
spring.redis.port=6379

这是最基础的三个配置(其实默认值就是这样,就算不写也可以)。当然,还有空闲连接数,超时时间,最大连接数等参数,我这里都没有设置,在生产项目中,根据实际情况设置。

RedisCacheConfig

新建RedisCacheConfig.class

@Configuration
@EnableCaching
public class RedisCacheConfig { /**
* 缓存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
} }

如果要设置缓存管理器所管理的缓存名字,RedisCacheManager构造方法提供一个可变参数的构造器:

测试

新建一个MockService.java,代码如下:

@Service
public class MockService { /**
* value 缓存的名字,与cacheName是一个东西
* key 需要缓存的键,如果为空,则会根据参数自动拼接
* 写法:SpEL 表达式
*/
@Cacheable(value = "listUsers", key = "#username")
public List<String> listUsers(String username) {
System.out.println("执行了listUsers方法");
return Arrays.asList("Happyjava", "Hello-SpringBoot", System.currentTimeMillis() + "");
} }

新建一个TestController.java,代码如下:

@RestController
public class TestController { private final MockService mockService; public TestController(MockService mockService) {
this.mockService = mockService;
} @GetMapping(value = "/listUsers")
public Object listUsers(String username) {
return mockService.listUsers(username);
} }

请求接口:

Redis中的数据:

原创声明

本文发布于掘金号【Happyjava】。Happy的掘金地址:https://juejin.im/user/5cc2895df265da03a630ddca,Happy的个人博客:http://blog.happyjava.cn。欢迎转载,但须保留此段声明。

关注公众号领资料

搜索公众号【Happyjava】,回复【电子书】和【视频】,即可获取大量优质电子书和大数据、kafka、nginx、MySQL等视频资料

【快学SpringBoot】Spring Cache+Redis实现高可用缓存解决方案的更多相关文章

  1. Redis主从高可用缓存

    nopCommerce 3.9 大波浪系列 之 使用Redis主从高可用缓存   一.概述 nop支持Redis作为缓存,Redis出众的性能在企业中得到了广泛的应用.Redis支持主从复制,HA,集 ...

  2. nopCommerce 3.9 大波浪系列 之 使用Redis主从高可用缓存

    一.概述 nop支持Redis作为缓存,Redis出众的性能在企业中得到了广泛的应用.Redis支持主从复制,HA,集群. 一般来说,只有一台Redis是不可行的,原因如下: 单台Redis服务器会发 ...

  3. 【快学springboot】13.操作redis之String数据结构

    前言 在之前的文章中,讲解了使用redis解决集群环境session共享的问题[快学springboot]11.整合redis实现session共享,这里已经引入了redis相关的依赖,并且通过spr ...

  4. 【快学springboot】8.JPA乐观锁OptimisticLocking

    介绍 当涉及到企业应用程序时,正确地管理对数据库的并发访问是至关重要的.为此,我们可以使用Java Persistence API提供的乐观锁定机制.它导致在同一时间对同一数据进行多次更新不会相互干扰 ...

  5. 【快学springboot】12.实现拦截器

    前言 之前在[快学springboot]6.WebMvcConfigurer配置静态资源和解决跨域里有用到WebMvcConfigurer接口来实现静态资源的映射和解决跨域请求,并且在文末还说了Web ...

  6. 【快学springboot】4.接口参数校验

    前言 在开发接口的时候,参数校验是必不可少的.参数的类型,长度等规则,在开发初期都应该由产品经理或者技术负责人等来约定.如果不对入参做校验,很有可能会因为一些不合法的参数而导致系统出现异常. 上一篇文 ...

  7. Redis Sentinel安装与部署,实现redis的高可用

    前言 对于生产环境,高可用是避免不了要面对的问题,无论什么环境.服务,只要用于生产,就需要满足高可用:此文针对的是redis的高可用. 接下来会有系列文章,该系列是对spring-session实现分 ...

  8. Redis Cluster高可用集群在线迁移操作记录【转】

    之前介绍了redis cluster的结构及高可用集群部署过程,今天这里简单说下redis集群的迁移.由于之前的redis cluster集群环境部署的服务器性能有限,需要迁移到高配置的服务器上.考虑 ...

  9. Redis Cluster高可用集群在线迁移操作记录

    之前介绍了redis cluster的结构及高可用集群部署过程,今天这里简单说下redis集群的迁移.由于之前的redis cluster集群环境部署的服务器性能有限,需要迁移到高配置的服务器上.考虑 ...

随机推荐

  1. vue中style下scope的使用和坑

    在vue组件中,为了使样式私有化(模块化),不对全局造成污染,可以在style标签上添加scoped属性以表示它的只属于当下的模块,这是一个非常好的举措,但是为什么要慎用呢?因为在我们需要修改公共组件 ...

  2. git 提交的时候 建立排除文件夹或者文件

    1.在Git的根仓库下 touch .gitignore 2.编辑这个文件

  3. codeforces 962F.simple cycle(tarjan/点双连通分量)

    题目连接:http://codeforces.com/contest/962/problem/F 题目大意是定义一个simple cycle为从一个节点开始绕环走一遍能经过simple cycle内任 ...

  4. c#项目调用Python模块的方法

    将Python模块用pyinstaller打包成exe程序 下载安装UPX((http://upx.sourceforge.net/)) ,并把路径加到环境变量中. UPX是开源的加壳和压缩exe的程 ...

  5. opencv:自适应阈值

    #include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace st ...

  6. Go计时器

    1. NewTimer package main import ( "time" "fmt" ) func main() { /* 1. func NewTim ...

  7. touch命令修改时间

    实例[rhel7]: [root@localhost test]# stat 1.txt 文件:"1.txt" 大小:0 块:0 IO 块:4096 普通空文件设备:fd00h/6 ...

  8. hadoop学习笔记(六):hadoop全分布式集群的环境搭建

    本文原创,如需转载,请注明作者以及原文链接! 一.前期准备: 1.jdk安装        不要用centos7自带的openJDK2.hostname    配置       配置位置:/etc/s ...

  9. C语言字符串类型转换为double浮点数类型

    #include <stdio.h>#include <stdlib.h>char *record; double re = atof(record); 使用 atof()函数 ...

  10. SSHException: Error reading SSH protocol banner

    当我在使用ssh  远程connect 另一台机器的server 时出现了错误,错误如下,起初以为是自己代码写的有问题,后来本地了一下看了跑的没问题,我就开始根据报错去查寻原因, 起初在论坛博客看到这 ...