简介

此案例中使用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的更多相关文章

  1. Spring Boot(十一)Redis集成从Docker安装到分布式Session共享

    一.简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API,Redis也是技术领域使用最为广泛的存储中间件,它是 ...

  2. Spring+Redis集成+关系型数据库持久化

    本篇文章主要介绍了"Spring+Redis集成+关系型数据库持久化",主要涉及到Spring+Redis集成+关系型数据库持久化方面的内容,对于Spring+Redis集成+关系 ...

  3. Spring Maven项目集成Springboot

    Maven管理的Spring项目,准备集成Springboot做接口 1.Springboot对Spring有版本要求 我用的Springboot版本:1.4.5.RELEASE,对应Spring的版 ...

  4. redis整合springboot的helloworld

    引入依赖 compile 'org.springframework.boot:spring-boot-starter-data-redis' 使用redis有两种方法 1.Jedis Jedis je ...

  5. Spring Boot Redis 集成配置(转)

    Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...

  6. 实战:docker搭建FastDFS文件系统并集成SpringBoot

    实战:docker搭建FastDFS文件系统并集成SpringBoot 前言 15年的时候,那时候云存储还远远没有现在使用的这么广泛,归根结底就是成本和安全问题,记得那时候我待的公司是做建站开发的,前 ...

  7. Docker运行Mysql,Redis,SpringBoot项目

    Docker运行Mysql,Redis,SpringBoot项目 1.docker运行mysql 1.1拉取镜像 1.2启动容器 1.3进入容器 1.4开启mysql 1.5设置远程连接 1.6查看版 ...

  8. 【redis】-- springboot集成redis及使用

    springboot自动配置的redis并不是特别好用,所以需要我们使用原生的jedis, 1.添加依赖 2.在application文件中配置 # Redis服务器地址 redis.host= # ...

  9. SpringBoot微服务电商项目开发实战 --- 模块版本号统一管理及Redis集成实现

    上一篇文章总结了基于SpringBoot实现分布式微服务下的统一配置.分环境部署配置.以及服务端模块的分离(每一个提供者就是一个独立的微服务).微服务落地.Dubbo整合及提供者.消费者的配置实现.本 ...

随机推荐

  1. VR AR MR的未来

    VR:VR(Virtual Reality,即虚拟现实,简称VR),是由美国VPL公司创建人拉尼尔(Jaron Lanier)在20世纪80年代初提出的.其具体内涵是:综合利用计算机图形系统和各种现实 ...

  2. TSS任务状态段

    TSS (任务状态段)的作用及结构   1.什么是TSS TSS全称Task State Segment ,是操作系统在进行进程切换时保存进程现场信息的段 2.TSS什么时候用,有什么用 TSS在任务 ...

  3. 「Codeforces 79D」Password

    Description 有一个 01 序列 \(a_1,a_2,\cdots,a_n\),初始时全为 \(0\). 给定 \(m\) 个长度,分别为 \(l_1\sim l_m\). 每次可以选择一个 ...

  4. 分布式抽奖秒杀系统,DDD架构设计和实现分享

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.用大项目,贯穿知识体系 写CRUD.堆API.改屎山⛰,熬多少个996也只是成为重复的螺丝 ...

  5. Ditto剪贴板增强工具

    1.简介 Ditto是一款强大的Windows剪贴板增强工具,它支持64位操作系统,而且完全免费,绿色开源,支持中文,而且还有免安装的绿色版本. 开启Ditto后,不会有任何程序界面出现,它只是默默地 ...

  6. Windows实现桌面录屏、指定窗口录制直播,低延时,H5页面播放

    接着前面记录的3种方式实现桌面推流直播: 1.Windows 11实现录屏直播,搭建Nginx的rtmp服务 的方式需要依赖与Flash插件,使用场景有限 2.Windows 11实现直播,VLC超简 ...

  7. Docker下安装Elasticsearch、ik分词器、kibana

    1:使用docker拉取Elasticsearch镜像 docker pull elasticsearch:7.12.0(不加版本号默认是最新版本) 2:查看是否成功下载镜像 docker image ...

  8. vue - 搭建 webapp 自适应项目-使用 vant 组件库 并 可自动调节大小

    1.创建个vue 项目,这里不详细写怎么创建,参考 vue - 指令创建 vue工程 - 岑惜 - 博客园 (cnblogs.com) https://www.cnblogs.com/c2g52013 ...

  9. 使用yum安装php*时报错的解决办法

    # yum -y install php* 注意: php53-odbc64-5.3.3-2.el5.x86_64 from base has depsolving problems  -->  ...

  10. 第10组 Beta冲刺 (3/5)(组长)

    1.1基本情况 ·队名:今晚不睡觉 ·组长博客:https://www.cnblogs.com/cpandbb/p/14018630.html ·作业博客:https://edu.cnblogs.co ...