Redis集成SpringBoot
简介
此案例中使用Centos7+redis+SpringBoot。
redis安装 https://www.cnblogs.com/xiaofengshan/p/15860447.html
添加依赖
<!--redis需要依赖前-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!--redis需要依赖后-->
配置文件
- Yml配置
spring:
redis:
#Redis服务器连接密码(默认为空)
# username: root
# password: 123QWEqwe
host: 192.168.101.110
port: 6379
#连接超时时间(毫秒)
timeout: 30000
jedis:
pool:
# 连接池中的最小空闲连接
min-idle: 2
# 连接池中的最大空闲连接
max-idle: 10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池最大连接数(使用负值表示没有限制)
max-active: 1000
- 代码配置
import java.lang.reflect.Method;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
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.connection.jedis.JedisConnectionFactory;
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.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
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);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
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);
// 配置序列化(解决乱码的问题),过期时间10秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
注意:外部访问redis的前提是把redis配置文件中的 protected-mode yes,改为 protected-mode no 这样redis才允许外部访问
测试案例
import com.yxkj.redisdemo.entity.TBICXX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.List;
/**
* @description:
* @projectName:FoundationStudy
* @see:com.yxkj.springbootdemo.dao
* @author:zhuyang
* @createTime:2021/10/31 21:45
* @version:1.0 mysql
*/
@Repository
@Slf4j
public class TBAddressDao {
@Resource
private JdbcTemplate jdbcTemplate;
/**
* @Description:
* @Author: zhuyang
* @Date: 2022-02-04
* @Param:
* @return:
* 根据方法对其返回结果进行缓存,下次请求时,如果缓存存在,则直接读取缓存数据返回;
* 如果缓存不存在,则执行方法,并把返回的结果存入缓存中。一般用在查询方法上。
* K值生成规则 value::key
**/
@Cacheable(value = "getId", key = "#id")
public List<TBICXX> getId(String id){
log.info("-----进入查询方法----");
String sql="SELECT * FROM YXHIS..TBICXX WHERE CICID=?";
List<TBICXX> collect = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(TBICXX.class),id);
return collect;
}
/**
* @Description:
* @Author: zhuyang
* @Date: 2022-02-04
* @Param:
* @return:
* @CacheEvict是用来标注在需要清除缓存元素的方法或类上的。
* 当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。
* @CacheEvict可以指定的属性有value、key、condition、allEntries和beforeInvocation。
* 其中value、key和condition的语义与@Cacheable对应的属性类似。
* 即value表示清除操作是发生在哪些Cache上的(对应Cache的名称);
* key表示需要清除的是哪个key,如未指定则会使用默认策略生成的key;
* condition表示清除操作发生的条件。下面我们来介绍一下新出现的两个属性allEntries和beforeInvocation。
*
* allEntries是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。
* 当指定了allEntries为true时,Spring Cache将忽略指定的key,
* 而是根据指定的value属性进行匹配,清除所有value相同的元素
* 有的时候我们需要Cache一下清除所有的元素,这比一个一个清除元素更有效率。
**/
@CacheEvict(value = "getId", allEntries=true,key = "#id")
public Integer updateById(String username,String id) {
log.info("-----进入更新方法----");
String sql="UPDATE YXHIS..TBICXX SET CXM=? WHERE CICID=?";
int update = jdbcTemplate.update(sql, username,id);
return update;
}
/**
* @Description:
* @Author: zhuyang
* @Date: 2022-02-04
* @Param:
* @return:
* 使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。
* 其他方法可以直接从响应的缓存中读取缓存数据,
* 而不需要再去查询数据库。一般用在新增方法上。
* 一般不使用
**/
@CachePut(value = "getId")
public Integer insertICXX(TBICXX tbicxx) throws Exception {
log.info("-----进入增加方法----");
String sql="insert into YXHIS..TBICXX(CICID,CXM,CXB,CBAH,CYLBX,IGRYH,BYXQ) VALUES(?,?,?,?,?,?,?)";
int update = jdbcTemplate.update(sql, tbicxx.getCICID(), tbicxx.getCXM(), tbicxx.getCXB(), tbicxx.getCBAH(), tbicxx.getCYLBX(), tbicxx.getIGRYH(), tbicxx.getBYXQ());
return update;
}
}
Gitee地址
https://gitee.com/zhuayng/foundation-study/tree/develop/DataDemo/RedisDemo
Redis集成SpringBoot的更多相关文章
- Spring Boot(十一)Redis集成从Docker安装到分布式Session共享
一.简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API,Redis也是技术领域使用最为广泛的存储中间件,它是 ...
- Spring+Redis集成+关系型数据库持久化
本篇文章主要介绍了"Spring+Redis集成+关系型数据库持久化",主要涉及到Spring+Redis集成+关系型数据库持久化方面的内容,对于Spring+Redis集成+关系 ...
- Spring Maven项目集成Springboot
Maven管理的Spring项目,准备集成Springboot做接口 1.Springboot对Spring有版本要求 我用的Springboot版本:1.4.5.RELEASE,对应Spring的版 ...
- redis整合springboot的helloworld
引入依赖 compile 'org.springframework.boot:spring-boot-starter-data-redis' 使用redis有两种方法 1.Jedis Jedis je ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- 实战:docker搭建FastDFS文件系统并集成SpringBoot
实战:docker搭建FastDFS文件系统并集成SpringBoot 前言 15年的时候,那时候云存储还远远没有现在使用的这么广泛,归根结底就是成本和安全问题,记得那时候我待的公司是做建站开发的,前 ...
- Docker运行Mysql,Redis,SpringBoot项目
Docker运行Mysql,Redis,SpringBoot项目 1.docker运行mysql 1.1拉取镜像 1.2启动容器 1.3进入容器 1.4开启mysql 1.5设置远程连接 1.6查看版 ...
- 【redis】-- springboot集成redis及使用
springboot自动配置的redis并不是特别好用,所以需要我们使用原生的jedis, 1.添加依赖 2.在application文件中配置 # Redis服务器地址 redis.host= # ...
- SpringBoot微服务电商项目开发实战 --- 模块版本号统一管理及Redis集成实现
上一篇文章总结了基于SpringBoot实现分布式微服务下的统一配置.分环境部署配置.以及服务端模块的分离(每一个提供者就是一个独立的微服务).微服务落地.Dubbo整合及提供者.消费者的配置实现.本 ...
随机推荐
- Chapter 12 IP Weighting and Marginal Structural Model
目录 12.1 The causal question 12.2 Estimating IP weights via modeling 12.3 Stabilized IP weights 12.4 ...
- An Introduction to Measure Theory and Probability
目录 Chapter 1 Measure spaces Chapter 2 Integration Chapter 3 Spaces of integrable functions Chapter 4 ...
- nginx -g "daemon off;" 你学废了吗?
去年的时候写了一篇原创<前后端分离,如何在前端项目中动态插入后端API基地址?(in docker)>, 我自认为这篇生产实践是对大前端. 容器化.CI/CD的得意之作. 对于前后端分离的 ...
- IOS 如何获取app更新链接 如【itms-apps://itunes.apple.com/cn/app/id1362432761?mt=8】
这是iTunes接口地址 ,有兴趣可以看一下,我们要用到的接口如下,xxx 处换成自己 App 的 AppId ,AppId 可以在 iTunes Connect 里面看到. http://itune ...
- 新手入门typeScript
强类型与弱类型(类型安全) 强类型不允许随意的隐士类型转换,而弱类型是允许的 变量类型允许随时改变的特点,不是强弱类型的差异 静态类型与动态类型(类型检查) 静态类型:一个变量声明时它的类型就是明确的 ...
- windows下的Python的下载与安装
Python的下载 Python下载要去官网下载,xdm,这里是网址 www.python.org 因为是外网所以打开下载会慢一些(不要着急的说) 这是python官网界面,跟着图片去下载(因为我这会 ...
- C# 绘制印章
最近有个.net core的项目要绘制印章功能,一个公司印章,一个个人印章,于是抽了点时间自己写了一个,现在分享出来 using System; using System.Collections.Ge ...
- 函数实现将 DataFrame 数据直接划分为测试集训练集
虽然 Scikit-Learn 有可以划分数据集的函数 train_test_split ,但在有些特殊情况我们只希望它将 DataFrame 数据直接划分为 train, test 而不是像 tr ...
- 制作JavaCV应用依赖的基础Docker镜像(CentOS7+JDK8+OpenCV4)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- 【Java】数组
文章目录 数组 一.数组的定义 二.数组的声明与创建 三.内存分析 四.三种初始化 五.数组的四个基本特点 六.数组边界 七.数组的使用 八.多维数组 九.Arrays类 十.稀疏数组 数组 一.数组 ...