spring boot集成redis缓存
spring boot项目中使用redis作为缓存。
先创建spring boot的maven工程,在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
在application.properties中添加配置
server.port:9000 #服务启动的端口
spring.redis.database=0 #redis数据库的索引,默认为0
spring.redis.host=192.168.133.130
#spring.redis.password=
spring.redis.port=6379
spring.redis.pool.max-idle=8 #最大空闲链接数
spring.redis.pool.min-idle=0 #最小空闲连接数
spring.redis.pool.max-active=8 #连接池最大连接数,负数表示无最大连接数
spring.redis.pool.max-wait=-1 #连接池最大阻塞等待时间,负数表示没有
#spring.redis.sentinel.master= #主节点
#spring.redis.sentinel.nodes= #
spring.data.mongodb.host=192.168.133.130
spring.data.mongodb.port=27017
spring.data.mongodb.database=fzk
在启动类中添加注解
@SpringBootApplication
@EnableCaching
public class Main { public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
}
@EnableCaching会为每个bean中被 @Cacheable
, @CachePut
and @CacheEvict修饰的public方法进行缓存操作。
缓存的用法
@Cacheable(value = "test", key = "'user_'.concat(#root.args[0])")
public User getUser(String userId) {
System.out.println("in getUser");
User user = new User();
user.setId(userId);
user.setPassword("passwd");
user.setUsername("username"); return user;
}
这个方法在userId相同形同的情况下,第一次调用的时候会执行方法,以后每次在调用的时候会读取缓存中的数据。
缓存的注解介绍:
@Cacheable
这个注解,会每次先检查是否执行过这个方法,在从缓存数据库中查看key是否相等,如果找到了,从缓存中读取,没有匹配的那么执行该方法,将结果缓存。
缓存都是通过key-value进行储存的,value或cacheNames必须指定(value是cacheNames的别名),指定多个value用(value = {"value1", "value2"})如果没有指定key,spring会提供一个默认的KeyGenerator,这个KeyGenerator根据参数生成key,如果方法没有参数返回KeyGenerator.EMPTY,如果有一个参数返回这个实例,如果有多个参数返回包含这些参数的SimpleKey。可以通过继承CachingConfigurerSupport自己指定KeyGenerator,类上加@Configuration注解。也可以像上面那样自己指定key,需要了解SPEL表达式。
多线程的情况下,可能同时会有多个线程同时进入一个没被缓存过的方法,这样会导致多个线程都会执行一遍方法,sync="true"会将第一次计算返回值的这个方法lock,计算完成后将结果缓存
@Cacheable(value="foos", sync="true")
public Foo executeExpensiveOperation(String id) {...}
在某些情况下,可能并不想把结果进行缓存,可通过condition进行筛选
@Cacheable(value="book", condition="#name.length() < 32")
public Book findBook(String name)
上面的#root表示的是返回值,其他一些可用的参数(来自spring官网)
@CachePut
每次都会执行该方法,并将结果进行缓存。用法与@Cacheable用法一致。
@CacheEvict
用于将清空缓存,可以指定key, value, condition,这几个的用法与上面介绍的一致。key和condition可以为空,如果为空,表示用默认策略。
@CacheEvict(value="books", allEntries=true, beforeInvocation=true)
public void loadBooks(InputStream batch)
allEntries=true表示清空books下的所有缓存,默认为false,beforeInvocation=true表示是否在方法执行前就清空缓存,默认为false。
@Caching
可以包含上面介绍的三个注解,key-value分别对应(cachable=[@Cacheable], put=[@CachePut], evict=[@CacheEvict])
@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)
@CacheConfig
是一个类级的注解
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository { @Cacheable
public Book findBook(ISBN isbn) {...}
}
这样类下的每个方法的缓存都用的是books,还可以指定自定义的KeyGenerator和CacheManager。
自定义缓存注解
通过使用上面的注解作为元直接实现自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Cacheable(value="books", key="#isbn")
public @interface SlowService {
}
这样我们就可以直接使用@SlowService作为注解
@SlowService
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
与下面的注解功能相同
@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
还有一点上面没说到的是spring用CacheManager管理缓存
这里用到的redis,所以肯定是用的RedisCacheManager,同样,我们也可以重新配置一下RedisCacheManager,在这里我们也可以配置一些参数,例如过期时间等等。
上面说到过默认的key生成器,我们同样可以定义自己的KeyGenerator,下面是实现
import java.lang.reflect.Method; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
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 com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; @Configuration
public class RedisConfig extends CachingConfigurerSupport { @Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... 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 CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); return cacheManager;
}
}
生成CacheManager用到的RedisTemplate同样可以自定义,这个主要是与redis数据库连接用的
spring boot集成redis缓存的更多相关文章
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
[本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...
- Spring Boot 2.X(六):Spring Boot 集成Redis
Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...
- SpringBoot(十一): Spring Boot集成Redis
1.在 pom.xml 中配置相关的 jar 依赖: <!-- 加载 spring boot redis 包 --> <dependency> <groupId>o ...
- spring boot集成redis基础入门
redis 支持持久化数据,不仅支持key-value类型的数据,还拥有list,set,zset,hash等数据结构的存储. 可以进行master-slave模式的数据备份 更多redis相关文档请 ...
- Spring Boot 结合 Redis 缓存
Redis官网: 中:http://www.redis.cn/ 外:https://redis.io/ redis下载和安装 Redis官方并没有提供Redis的Windows版本,这里使用微软提供的 ...
- Spring Boot自定义Redis缓存配置,保存value格式JSON字符串
Spring Boot自定义Redis缓存,保存格式JSON字符串 部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642 ...
- 【spring boot】【redis】spring boot 集成redis的发布订阅机制
一.简单介绍 1.redis的发布订阅功能,很简单. 消息发布者和消息订阅者互相不认得,也不关心对方有谁. 消息发布者,将消息发送给频道(channel). 然后是由 频道(channel)将消息发送 ...
- SpringBoot入门系列(七)Spring Boot整合Redis缓存
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...
- spring boot集成redis实现session共享
1.pom文件依赖 <!--spring boot 与redis应用基本环境配置 --> <dependency> <groupId>org.springframe ...
随机推荐
- 什么是 end-to-end 神经网络?——知乎解答
什么是 end-to-end 神经网络? https://www.zhihu.com/question/51435499 解答1 张旭 像机器一样学习,像人一样生活 YJango 等 端到端指的是 ...
- SQLAllocStmt与SQLFreeStmt
1.申请语句句柄 SQLAllocStmt函数为应用程序分配语句句柄,其格式为:RETCODE SQLAllocStmt(HDBC hdbc, HSTMT FAR * phstmt) 其中, hdbc ...
- JMETER 不同线程组 变量值 的参数传递(转)
线程组 1 在线程组1中使用__setProperty函数设置jmeter属性值(此值为全局变量值),将所需变量值如${token}设置为jmeter属性值,即newtoken,示例: 1.添加- ...
- hdu4045(递推)
不会斯特林数的只能用递推思想了,结果发现推出来的就是斯特林数... #include <stdio.h> #include <stdlib.h> #include <st ...
- mysql如何判断一个字符串是否包含另外一个字符串?
转自:http://blog.csdn.net/hechurui/article/details/49278493 判断子字符串在父字符串当中的索引: SELECT LOCATE("b&qu ...
- linux的bash与sh的区别
转自:https://zhidao.baidu.com/question/305415121.html https://zhidao.baidu.com/question/176780008.html ...
- Thrift初试
Restful 基于 Http 进行通讯. 开放.标准.简单.兼容性升级容易: 性能略低.在 QPS 高或者对响应时间要求苛刻的服务上,可以用 RPC,RPC采用二进制传输.TCP 通讯,所以通常性能 ...
- javamail+postfix发送邮件
由于在做项目时,需要用到邮箱服务.但是不想使用163,qq的,所以就自己搭一个邮箱服务器. 在搜索资料发现postfix是个不错的选择,于是就开始配置了. 这是我搜到的最全的的教程了:http://w ...
- delphi----Tstringlist,将有符号的数据变成数组"aaa,bbb,ccc"---->list[0]=aaa,list[1]=bbb
//TStringList 常用方法与属性: var List: TStringList; i: Integer; begin List := TStringList.Create; ...
- python 里面的单下划线与双下划线的区别(私有和保护)
Python 用下划线作为变量前缀和后缀指定特殊变量. _xxx 不能用'from moduleimport *'导入 __xxx__ 系统定义名字 __xxx 类中的私有变量名 核心风格:避免用下划 ...