springboot使用redis(从配置到实战)
概述
springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring支持的注解进行访问缓存.
准备工作
pom.xml
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>RELEASE</version>
</dependency>
application.properties
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
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=0
Redis配置类
package cn.chenlove.config;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Bean
public JedisPool redisPoolFactory() {
Logger.getLogger(getClass()).info("JedisPool注入成功!!");
Logger.getLogger(getClass()).info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
return jedisPool;
}
}
可以看出,我们这里主要配置了两个东西,cacheManager方法配置了一个缓存名称,它的名字叫做thisredis,当我们要在方法注解里面使用到它的时候,就要根据名称进行区分不同缓存.同时设置了缓
存的过期时间.redisTemplate则是比较常见的,我们设置了RedisTemplate,因此在代码里面,我们也可以通过@Autowired注入RedisTemplate来操作redis.
使用
接下来就是如何使用注解啦,这一步反而是最简单的.其实只用到了两个注解,@Cacheable和@CacheEvict.第一个注解代表从缓存中查询指定的key,如果有,从缓存中取,不再执行方法.如果没有则执
行方法,并且将方法的返回值和指定的key关联起来,放入到缓存中.而@CacheEvict则是从缓存中清除指定的key对应的数据.使用的代码如下:
//有参数
@Cacheable(value="thisredis", key="'users_'+#id")
public User findUser(Integer id) {
User user = new User();
user.setUsername("hlhdidi");
user.setPassword("123");
user.setUid(id.longValue());
System.out.println("log4j2坏啦?");
logger.info("输入user,用户名:{},密码:{}",user.getUsername(),user.getPassword());
return user;
}
@CacheEvict(value="thisredis", key="'users_'+#id",condition="#id!=1")
public void delUser(Integer id) {
// 删除user
System.out.println("user删除");
}
//无参数
@RequestMapping("/get")
@Cacheable(value="thisredis")
@ResponseBody
public List<User> xx(){
return userMapper.selectAll();
}
@RequestMapping("/get3")
@CacheEvict(value="thisredis")
@ResponseBody
public String xx3(){
return "ok";
}
可以看出,我们用@Cacheable的value属性指定具体缓存,并通过key将其放入缓存中.这里key非常灵活,支持spring的el表达式,可以通过方法参数产生可变的key(见findUser方法),也可以通过其指定在
什么情况下,使用/不使用缓存(见delUser方法).
springboot使用redis(从配置到实战)的更多相关文章
- springboot使用redis的配置application.yml连接池以及存取
第一步:添加pom文件依赖: <!-- redis --> <dependency> <groupId>redis.clients</groupId> ...
- springBoot集成Redis遇到的坑(择库)源码分析为什么择库失败
提示: springboot提供了一套链接redis的api,也就是个jar包,用到的连接类叫做LettuceConnectionConfiguration,所以我们引入pom时是这样的 <de ...
- SpringBoot整合Redis并完成工具类
SpringBoot整合Redis的资料很多,但是我只需要整合完成后,可以操作Redis就可以了,所以不需要配合缓存相关的注解使用(如@Cacheable),而且我的系统框架用的日志是log4j,不是 ...
- spring boot 学习(十四)SpringBoot+Redis+SpringSession缓存之实战
SpringBoot + Redis +SpringSession 缓存之实战 前言 前几天,从师兄那儿了解到EhCache是进程内的缓存框架,虽然它已经提供了集群环境下的缓存同步策略,这种同步仍然需 ...
- 九、springboot整合redis二之缓冲配置
1.创建Cache配置类 @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSu ...
- SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码
创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...
- Spring Data Redis 详解及实战一文搞定
SDR - Spring Data Redis的简称. Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能.它提供了与商店互动的低级别和高级别抽象,使用户免受 ...
- springboot整合redis——redisTemplate的使用
一.概述 相关redis的概述,参见Nosql章节 redisTemplate的介绍,参考:http://blog.csdn.net/ruby_one/article/details/79141940 ...
- java架构之路-(Redis专题)SpringBoot连接Redis超简单
上次我们搭建了Redis的主从架构,哨兵架构以及我们的集群架构,但是我们一直还未投入到实战中去,这次我们用jedis和springboot两种方式来操作一下我们的redis 主从架构 如何配置我上次已 ...
随机推荐
- php使用curl模拟post请求
废话不多说,直接上代码,做个笔记. $url="http://localhost/header_server.php"; $body = array("mobile&qu ...
- P2014选课
洛谷P2014选课 一道树形DP题. f[i][j]表示i个点选j门课程的最大学分. 递推方程: for(int a=n;a>0;a--)//总共选择多少 for(int b=0;b<a; ...
- 项目启动报错 The server time zone value '�й���ʱ��' is unrecognize...
背景介绍: 把项目在新的电脑上运行,MySQL版本不同出现错误 错误: 报错The server time zone value '�й���ʱ��' is unrecognized or repr ...
- 第三篇--如何修改exe文件版本号和文件信息
控制台程序添加版本信息方法: 项目右键 Add-->Resource-->选择Version-->new,然后就可以修改里面的信息了,重新编译一下就OK.
- Discuz 7.x/6.x 全局变量防御绕过导致代码执行
地址 http://192.168.49.2:8080/viewthread.php?tid=13&extra=page%3D1 安装成功后,找一个已存在的帖子,向其发送数据包,并在Cooki ...
- 什么是软件的CLI安装
Websoft9 在进行开源软件的集成与自动化安装研究过程中发现有些软件有CLI安装模式,例如Gitlab CLI版本.Ghost CLI.PHP CLI等,CLI安装是什么意思? CLI(Comma ...
- 自学linux——9.Linux的权限概述
Linux的权限概述 一. 权限概述 1.权限介绍 在多用户(可以不同时)计算机系统的管理中,权限是指某个特定的用户具有特定的系统资源使用权力,像是文件夹.特定系统指令的使用或存储量的限制 ...
- SpringBoot数据访问之整合Mybatis配置文件
环境搭建以及前置知识回顾 SpringBoot中有两种start的形式: 官方:spring-boot-starter-* 第三方:*-spring-boot-starter Mybatis属于第三方 ...
- P2470 压缩 TJ
前言 洛谷题解 题目传送门 正解:区间/线性 dp(本篇题解介绍线性做法) 人生第一道紫题! 也是今天考试看自闭了就没做的 T4,结果没想到是紫,虽然是一道水紫呢-- 考试的 T5 是跳房子,蓝题 q ...
- 单机版搭建kubernetes(K8s)
准备 云原生的概念越来越火,忍不住去看了看kubernetes,初次接触,晕晕乎乎的,于是不管三七二十一,先搭建个单机版的再说(没钱买服务器,目前也懒得装虚拟机),跑起来也算是第一步吧.网上教程一顿搜 ...