一、Springboot2.x关于配置redis作为缓存。

基本配置如下:

(1)在application.properties文件中

spring.redis.database=2 //第几个数据库,由于redis中数据库不止一个
spring.redis.host=localhost // 也可指定为127.0.0.1
spring.redis.port=6379 // 默认端口
spring.redis.password= // 默认为空 # springboot2.x以上如此配置,由于2.x的客户端是lettuce
# 单位要带上
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=10000ms
spring.redis.lettuce.shutdown-timeout=100ms # springboot1.x如此配置,由于1.x的客户端是jedis
#spring.redis.jedis.pool.max-active=8
#spring.redis.jedis.pool.min-idle=0
#spring.redis.jedis.pool.max-idle=8
#spring.redis.jedis.pool.max-wait=-1
#spring.redis.timeout=500

(2)在pom.xml中

<!--spring2.0集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<!-- redis依赖,2.0以上使用这个依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 缓存依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

(3)自定义缓存管理器RedisCacheConfig

package com.xf.spring_test.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.*; import java.time.Duration; @Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport { private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class); // 自定义key生成器
@Bean
public KeyGenerator keyGenerator(){
return (o, method, params) ->{
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName()); // 类目
sb.append(method.getName()); // 方法名
for(Object param: params){
sb.append(param.toString()); // 参数名
}
return sb.toString();
};
} // 配置缓存管理器
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(60)) // 60s缓存失效
// 设置key的序列化方式
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
// 设置value的序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
// 不缓存null值
.disableCachingNullValues(); RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build(); logger.info("自定义RedisCacheManager加载完成");
return redisCacheManager;
} /* @Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
logger.info("序列化完成!");
return redisTemplate;
}*/ // key键序列化方式
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
} // value值序列化方式
private GenericJackson2JsonRedisSerializer valueSerializer(){
return new GenericJackson2JsonRedisSerializer();
}
}

(4)在service的实现类中加入需要的注解,即可实现缓存数据

package com.xf.spring_test.service.impl;

import com.xf.spring_test.dao.PersonDao;
import com.xf.spring_test.domain.Person;
import com.xf.spring_test.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class UserServiceImpl implements UserService {
PersonDao personDao; public UserServiceImpl(PersonDao personDao) {
this.personDao = personDao;
} @Override
@Cacheable(cacheNames = "user")
public Person getUserById(Integer id) {
return personDao.getUserById(id);
} @Override
@Cacheable(cacheNames = "users")
public List<Person> getAllUser() {
return personDao.getAllUser();
} @Override
@CachePut(cacheNames = "updateUser", condition = "#person!=null", unless = "#result>0")
public Integer editUser(Person person) {
return personDao.editUser(person);
} @Override
@CacheEvict(cacheNames = "delUser", allEntries = true, beforeInvocation = true,
condition = "#userId>0")
public Integer delUser(Integer userId) {
return personDao.delUser(userId);
}
}

二、注意事项

(1)要缓存的JAVA对象必须实现Serailizable接口

(2)必须要配置RedisCacheManager 来管理缓存

Springboot2.x使用redis作为缓存的更多相关文章

  1. springboot2.x整合redis实现缓存(附github链接)

    本文代码已提交github:    https://github.com/LCABC777/Springboot-redis(1)Springboot中使用redis操作的两种方式:lettuce和j ...

  2. springboot2.0整合redis作为缓存以json格式存储对象

    步骤1 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spr ...

  3. springboot2.0+redis实现消息队列+redis做缓存+mysql

    本博客仅供参考,本人实现没有问题. 1.环境 先安装redis.mysql 2.springboot2.0的项目搭建(请自行完成),本人是maven项目,因此只需配置,获取相应的jar包,配置贴出. ...

  4. SpringBoot2.X + SpringCache + redis解决乱码问题

    环境:SpringBoot2.X + SpringCache + Redis Spring boot默认使用的是SimpleCacheConfiguration,使用ConcurrentMapCach ...

  5. SpringBoot2.x整合Redis实战 4节课

    1.分布式缓存Redis介绍      简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/download          2.新手 ...

  6. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_39、SpringBoot2.x整合redis实战讲解

    笔记 3.SpringBoot2.x整合redis实战讲解 简介:使用springboot-starter整合reids实战 1.官网:https://docs.spring.io/spring-bo ...

  7. Redis实现缓存与分布式锁

    缓存与分布式锁 哪些数据适合放入缓存 即时性.数据一致性要求不高的 访问量大且更新频率不高的数据 选择redis做为缓存中间件 <dependency> <groupId>or ...

  8. SpringAOP与Redis搭建缓存

    近期项目查询数据库太慢,持久层也没有开启二级缓存,现希望采用Redis作为缓存.为了不改写原来代码,在此采用AOP+Redis实现. 目前由于项目需要,只需要做查询部分: 数据查询时每次都需要从数据库 ...

  9. redis清空缓存

    进入redis命令行 首先启动redis服务 redis-server /home/redis/redis_7901.conf redis-cli -p 7901(指定进入端口号为7901的redis ...

随机推荐

  1. 客户端相关知识学习(四)之H5页面如何嵌套到APP中

    Android原生如何渲染H5页面 Android与 H5 的交互方式大概有以下 1 种: 利用WebView进行交互(系统API) iOS原生如何渲染H5页面 iOS 与 H5 的交互方式大概有以下 ...

  2. 平时工作使用到的idea快捷键或者技巧

    平时工作使用到的idea快捷键或者技巧 alt+enter 快速导入包 alt+insert 快速生成setter和getter ctrl+alt+l 格式化代码 /**然后回车 快速生成文档注释 a ...

  3. CentOS7部署ntp服务器

    主机 角色 192.168.48.128 Server 192.168.48.129 Client 192.168.48.130 Client 所有主机安装ntp服务 yum install -y n ...

  4. Vue项目里添加特殊字体或 某些字体乱码的问题

    问题:有个西藏的项目因使用藏文,而出现乱码 (一开始不乱的,不知道后台怎么处理...后来不知道为啥,前端乱码了) 解决:字体ttf 格式已下载,在项目中全局引入了 @font-face { font- ...

  5. Ubuntu18.10中pip install mysqlclient 出现EnvironmentError: mysql_config not found错误

    Complete output from command python setup.py egg_info: sh: 1: mysql_config: not found Traceback (mos ...

  6. Linux 的帐号与群组:有效与初始群组、groups, newgrp

    关于群组: 有效与初始群组.groups, newgrp 认识了帐号相关的两个档案 /etc/passwd 与 /etc/shadow 之后,您或许还是会觉得奇怪, 那么群组的设定档在哪里?还有,在 ...

  7. IList,List<T>转换为DataTable 常用收藏

    List<info> infos = Dal.GetInfos(); DataTable dt = new DataTable(); dt.Columns.Add("cName& ...

  8. tp5.1引用第三方类库

    1.TP5第三方类库全部放在Extend目录内,如果是放在Extend目录下,则不需要再类库里声明namespace.直接 new \YourClass() 即可 2.如果你的类库在Extend的子目 ...

  9. 【LuoguP4081】[SCOI2015]小凸想跑步

    题目链接 题意 给你一个凸多边形,求出在其内部选择一个点,这个点与最开始输入的两个点形成的三角形是以该点对凸多边形三角剖分的三角形中面积最小的一个三角形的概率. Sol 答案就是 可行域面积与该凸多边 ...

  10. Unknown or unsupported command 'install'

    由于电脑中存在多个python,导致pip install numpy出现标题这样的错误 结局方案; 在想要的python文件夹中的Scripts,shift右键点开命令行,pip.exe insta ...