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

​  redis 作为一个高性能的内存数据库,如果不会用就太落伍了,之前在 node.js 中用过 redis,本篇记录如何将 redis 集成到 spring boot 中。提供 redis 操作类,和注解使用 redis 两种方式。主要内容如下:

  • docker 安装 redis
  • springboot 集成 redis
  • 编写 redis 操作类
  • 通过注解使用 redis

安装 redis

  通过 docker 安装,docker compose 编排文件如下:

# docker-compose.yml
version: "2"
services:
redis:
container_name: redis
image: redis:3.2.10
ports:
- "6379:6379"

  然后在docker-compose.yml所在目录使用docker-compose up -d命令,启动 redis。

集成 springboot

  说明:springboot 版本为 2.1.3

添加 maven 依赖

  只需添加spring-boot-starter-data-redis依赖即可,并排除 lettuce 依赖,然后引入 jedis 和 jedis 的依赖 commons-pool2

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

编写 springboot 配置文件

  配置文件如下:

server:
port: 8081
servlet:
context-path: /sso
spring:
application:
name: SSO
cache:
type: redis
redis:
database: 0
host: 192.168.226.5
port: 6379
# 有密码填密码,没有密码不填
password:
# 连接超时时间(ms)
timeout: 1000ms
# 高版本springboot中使用jedis或者lettuce
jedis:
pool:
# 连接池最大连接数(负值表示无限制)
max-active: 8
# 连接池最大阻塞等待时间(负值无限制)
max-wait: 5000ms
# 最大空闲链接数
max-idle: 8
# 最小空闲链接数
min-idle: 0

编写配置类

  配置类代码如下:

@EnableCaching//开启缓存
@Configuration
public class RedisConfig extends CachingConfigurerSupport { /**
* 设置缓存管理器,这里可以配置默认过期时间等
*
* @param connectionFactory 连接池
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(60));
//注意:请勿使用先new 配置对象,然后在调用entryTtl方法的方式来操作
//会导致配置不生效,原因是调用.entryTtl方法会返回一个新的配置对象,而不是在原来的配置对象上修改 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
return manager;
} @SuppressWarnings("all")
@Bean
public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
} //使用jedis连接池建立jedis连接工厂
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
logger.info("jedisConnectionFactory:初始化了");
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setMaxWaitMillis(maxWaitMillis);
config.setMaxTotal(maxActive);
//链接耗尽时是否阻塞,默认true
config.setBlockWhenExhausted(true);
//是否启用pool的jmx管理功能,默认true
config.setJmxEnabled(true);
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setPoolConfig(config);
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setDatabase(database);
factory.setTimeout(timeout);
return factory;
}
}

使用方法

  有两种方法来进行缓存操作,一种是在方法上添加缓存注解实现各种操作,一种是手动控制。个人比较喜欢手动控制,觉得这样都在自己的掌控中。

通过注解使用

  主要有以下 5 个注解:

  • @CacheConfig: 类级别缓存,设置缓存 key 前缀之类的
  • @Cacheable: 触发缓存入口
  • @CacheEvict: 触发移除缓存
  • @CachePut: 更新缓存
  • @Caching: 组合缓存

@CacheConfig

  该注解可以将缓存分类,它是类级别注解,主要用于给某个类的缓存全局配置,例子如下:

@CacheConfig(cacheNames = "redis_test")
@Service
public class RedisService {
//....
}

上面 CacheConfig 会给类下通过注解生成的 key 加上 redis_test 的前缀。

@Cacheable

  方法级别注解,根据 key 查询缓存:

  • 如果 key 不存在,将方法返回值缓存到 redis 中
  • 如果 key 存在,直接从缓存中取值

    例子如下:
    /**
* 缓存时间,首次查询后会缓存结果,key中的值可使用表达式计算.
* 如不提供key,将使用默认key构造方法生成一个key
* @return long
*/
@Cacheable(key = "'currentTime'")
public long getTime() {
return System.currentTimeMillis();
}

多次调用此段代码会发现每次返回的值都是一样的。

CachePut

  用于更新缓存,每次调用都会想 db 请求,缓存数据

  • 如果 key 存在,更新内容
  • 如果 key 不存在,插入内容

代码如下:

/**
* 一般用于更新查插入操作,每次都会请求db
*/
@CachePut(key = "'currentTime'+#id")
public long updateTime(String id) {
return System.currentTimeMillis();
}

每次调用此方法都会根据 key 刷新 redis 中的缓存数据。

@CacheEvict

  根据 key 删除缓存中的数据。allEntries=true 表示删除缓存中所有数据。

代码如下:

    @CacheEvict(key = "'currentTime'+#id",allEntries=false)
public void deleteTime(String id) {
}

@Caching

  本注解可将其他注解组合起来使用。比如下面的例子:

    //value属性为key指定前缀
@Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"),
@CachePut(value = "user", key = "'pass_'+#user.password")})
public User testCaching(User user) {
return user;
}

上面的代码执行后将在 redis 中插入两条记录。使用keys *将看到如下结果:

手动控制

  手动控制就相当于 mybatis 的手写 sql 语句,需要调用redisTemplate中的各种方法来进行缓存查询,缓存更新,缓存删除等操作。

  使用方法参见 util/RedisUtil 中的方法。redisTemplate基本可以实现所有的 redis 操作。

本篇原创发布于:springboot 整合 redis

项目源码:github

你知道如何在springboot中使用redis吗的更多相关文章

  1. 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧

    做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...

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

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

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

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

  4. SpringBoot中使用Redis

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

  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. 如何在.Net中使用Redis

    Redis是一个key-value存储系统.和Memcached类似,但是解决了断电后数据完全丢失的情况,而且她支持更多无化的value类型,除了和string外,还支持lists(链表).sets( ...

  8. spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架

    前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...

  9. 在SpringBoot中引入Redis

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

随机推荐

  1. getshell不用英文数字 或者不用下划线

    getshell不用英文字母和数字 上代码 实际代码没有echo strlen($code);我测试的时候加上去的 思路是eval执行getFlag函数. 过滤了字母和数字,长度得小于40 直接看pa ...

  2. Python2 HTMLTestRunner自动化测试报告美化

    python2 的测试报告美化,需要的同学直接用 #coding=utf-8 """ A TestRunner for use with the Python unit ...

  3. js 遍历对象属性(for in、Object.keys、Object.getOwnProperty) 以及高效地输出 js 数组

    js中几种遍历对象的方法,包括for in.Object.keys.Object.getOwnProperty,它们在使用场景方面各有不同. for in 主要用于遍历对象的可枚举属性,包括自有属性. ...

  4. 自己搭建一个记笔记的环境记录(leanote)

    一直在找一个开源的记笔记的软件,偶然看到leanote.竟然还是开源的,还是国人开发的果断mark了.自己在电脑上搭建了一个挺好玩的.可以记录一些不给别人看的小秘密. 下面是步骤记录,当然可以到官网上 ...

  5. DFS和BFS遍历的问题

    来自https://github.com/soulmachine/leetcode 广度优先搜索 输入数据:没有什么特征,不像dfs需要有递归的性质.如果是树/图,概率更大. 状态转换图:数或者DAG ...

  6. w3wp.exe占用cpu特别高

    w3wp.exe占用cpu特别高,百度了一下在任务管理器标记出PID可以看到进程号. 试了一下,发现一个xxx网站占用cpu特别高,然后就结束了下进程,再重启网站cpu一下子降下来. 很奇怪,还需要具 ...

  7. ansible中playbook使用

    palybook使用 ####yaml语法ansible中使用的yaml基础元素:变量Inventory条件测试迭代 playbook的组成结构InventoryModulesAd Hoc Comma ...

  8. 12小时制时间&&24小时制时间

    今天在获取时间的时候发现,插入到数据库中的时间,其中下午的时间直接显示01,02的样子...查了下资料发现了端倪, java.text.SimpleDateFormat f=new java.text ...

  9. Ionic2中使用第三方插件极光推送

    不同于Ionic1中插件的调用,Ionic2提供了Ionic Native.Ionic Native封装了一些常见的插件(如:Camera.Barcode Scanner等),这些插件的使用方式在官方 ...

  10. vscode编辑器开发react时,设置使emmet支持自定义组件

    "emmet.triggerExpansionOnTab": true 在vscode用户配置当中配置这个,就可以了