简介

此案例中使用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. CONTRASTIVE REPRESENTATION DISTILLATION

    目录 概 主要内容 超参数的选择 代码 Tian Y., Krishnan D., Isola P. CONTRASTIVE REPRESENTATION DISTILLATION. arXiv pr ...

  2. [opencv]KAZE、AKAZE特征检测、匹配与对象查找

    AkAZE是KAZE的加速版 与SIFT,SUFR比较: 1.更加稳定 2.非线性尺度空间 3.AKAZE速度更加快 4.比较新的算法,只有Opencv新的版本才可以用 AKAZE局部匹配介绍 1.A ...

  3. Elasticsearch单机安装Version7.10.1

    1.说明 Elasticsearch单机安装, 基于Elasticsearch的7.10.1版本, 在Linux上安装Elasticsearch单机, 使用安装包elasticsearch-7.10. ...

  4. LDAP服务端安装

    安装环境: 10.43.159.9 root/zdh1234 使用离线的yum源安装,如果机器重启过需要重新挂载镜像 mount /dev/cdrom /media/zidong/ 1.查看openl ...

  5. nginx及依赖包安装分享 百度网盘(pcre+openssl+zlib)

    链接:https://pan.baidu.com/s/1gggq1p-uZSmAw49o5xfl4g 提取码:ypoj 复制这段内容后打开百度网盘手机App,操作更方便哦 1.安装pcre 解压:ta ...

  6. Git_使用SSH密钥操作远端仓库

    git支持多种传输协议,ssh协议是其中一种. 初次使用git的用户要使用ssh协议大概需要三个步骤: 生成密钥 设置远程仓库(本文以github为例)上的公钥 把git的 remote url 修改 ...

  7. django 修改模型中默认字段类型

    在ADMIN页面实现一个密码框,模型中是CharField默认类型是textinput,实现方法是在admin.py中重写widgets. 来自为知笔记(Wiz)

  8. Centos7 安装 brctl 工具

    [root@docker-node1 ~]# brctl show -bash: brctl: command not found [root@docker-node1 ~]# yum -y inst ...

  9. PPT2010制作充电动画

    原文: https://www.toutiao.com/i6492264647318569486/ 启动PPT2010,新建一张空白幻灯片 选择"插入"选项卡,"插图&q ...

  10. POJ3090Visible Lattice Points

    http://poj.org/problem?id=3090 对于此题,观测点的数目,从小规模开始观察,可以得到每一个点,由一根无限长的绳子,绕着原点旋转,得到的第一个点.换另外一个思路,每一个观察到 ...