redis05 sprngboot整合redis

思维草图

redis的Java客户端

整合步骤

添加redis的pom依赖

<!-- 引入redis依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!-- 引入redis连接池的依赖 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>

配置文件配置

spring:redis:database: 0host: 127.0.0.1port: 6379password:timeout: 5000lettuce:pool:max-active: 32max-wait: -1max-idle: 16min-idle: 8

编写配置类

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}
}

编写redis工具类RedisUtil.java

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** Redis常用的一些操作** @author LH*/
@Component
public class RedisUtil {@Resourceprivate RedisTemplate<String, Object> redisTemplate;/*** 写入缓存*/public boolean set(final String key, Object value) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 写入缓存设置时效时间*/public boolean set(final String key, Object value, Long expireTime) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 更新缓存*/public boolean getAndSet(final String key, String value) {boolean result = false;try {redisTemplate.opsForValue().getAndSet(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 批量删除对应的value*/public void remove(final String... keys) {for (String key : keys) {remove(key);}}/*** 批量删除key*/public void removePattern(final String pattern) {Set<String> keys = redisTemplate.keys(pattern);if (CollectionUtils.isNotEmpty(keys)) {redisTemplate.delete(keys);}}/*** 删除对应的value*/public void remove(final String key) {if (exists(key)) {redisTemplate.delete(key);}}/*** 判断缓存中是否有对应的value*/public boolean exists(final String key) {Boolean isExists = redisTemplate.hasKey(key);return BooleanUtils.isTrue(isExists);}/*** 读取缓存*/public Object get(final String key) {ValueOperations<String, Object> operations = redisTemplate.opsForValue();return operations.get(key);}/*** 哈希 添加*/public void hmSet(String key, Object hashKey, Object value) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();hash.put(key, hashKey, value);}/*** 哈希获取数据*/public Object hmGet(String key, Object hashKey) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();return hash.get(key, hashKey);}/*** 列表添加*/public void lPush(String k, Object v) {ListOperations<String, Object> list = redisTemplate.opsForList();list.rightPush(k, v);}/*** 列表获取*/public List<Object> lRange(String k, long l, long l1) {ListOperations<String, Object> list = redisTemplate.opsForList();return list.range(k, l, l1);}/*** 集合添加*/public void addSet(String key, Object value) {SetOperations<String, Object> set = redisTemplate.opsForSet();set.add(key, value);}/*** 删除集合下的所有值*/public void removeSetAll(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();Set<Object> objectSet = set.members(key);if (objectSet != null && !objectSet.isEmpty()) {for (Object o : objectSet) {set.remove(key, o);}}}/*** 判断set集合里面是否包含某个元素*/public Boolean isMember(String key, Object member) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.isMember(key, member);}/*** 集合获取*/public Set<Object> setMembers(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.members(key);}/*** 有序集合添加*/public void zAdd(String key, Object value, double source) {ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();zset.add(key, value, source);}/*** 有序集合获取指定范围的数据*/public Set<Object> rangeByScore(String key, double source, double source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.rangeByScore(key, source, source1);}/*** 有序集合升序获取*/public Set<Object> range(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.range(key, source, source1);}/*** 有序集合降序获取*/public Set<Object> reverseRange(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.reverseRange(key, source, source1);}
}

redis Key过期处理事件

修改redis的配置文件

看一下notify-keyspace-events Ex是否被注释(默认是注释),放开注释即可。

修改RedisConfig.java

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @Description redis配置* @Author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig
{@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}/*** 开启监听redis Key过期事件*/@Beanpublic RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory){RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}
}

定义过期监听器RedisKeyExpireListener

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;/*** @Description redis过期监听器* @Author LH**/
@Slf4j
public class RedisKeyExpireListener extends KeyExpirationEventMessageListener
{public RedisKeyExpireListener(RedisMessageListenerContainer listenerContainer){super(listenerContainer);}@Overridepublic void onMessage(Message message, byte[] pattern){String expireKey = message.toString();// 根据过期的key处理对应的业务逻辑log.info(expireKey + "已过期-------------------");}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/517813.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

少儿编程机器人技术开发公司的创新之路

行业背景&#xff0c;国家政策利好 随着科技的不断发展&#xff0c;少儿编程机器人技术作为一种新兴的教育方式逐渐受到人们的关注。这项技术将编程与机器人技术相结合&#xff0c;通过互动性强、趣味性高的方式&#xff0c;帮助儿童学习编程知识&#xff0c;培养逻辑思维和创…

查看kafka消息消费堆积情况

查看主题命令 展示topic列表 ./kafka-topics.sh --list --zookeeper zookeeper_ip:2181描述topic ./kafka-topics.sh --describe --zookeeper zookeeper_ip:2181 --topic topic_name查看topic某分区偏移量最大&#xff08;小&#xff09;值 ./kafka-run-class.sh kafka.too…

像SpringBoot一样使用Flask - 6.多环境打包发布

接上文《像SpringBoot一样使用Flask - 5.统一处理&#xff08;日志、异常、响应报文&#xff09;》&#xff0c;一个小架子差不多了&#xff0c;就得看看怎么像SpringBoot多环境以及打包之后一个最终效果是怎样了。 一、写一个配置文件 class BaseConfig():LOCAL_ENV "p…

Hive Thrift Server

hive-site.xml配置文件 <property><name>hive.server2.thrift.bind.host</name><value>node1</value> </property>hive.server2.thrift.bind.host: This property determines the host address to which the HiveServer2 Thrift service …

管理类联考--复试--面试问题--底层逻辑

文章目录 了解面试官提问问题的背后逻辑&#xff0c;在面试时遇到&#xff0c;即使不懂&#xff0c;也能往边边靠近哈一句顶一万句自我介绍 了解面试官提问问题的背后逻辑&#xff0c;在面试时遇到&#xff0c;即使不懂&#xff0c;也能往边边靠近哈 “你最有挑战性的事是啥”…

MIT 6.S081---Lab: Multithreading

Uthread: switching between threads (moderate) 修改uthread.c&#xff0c;在thread中新增context字段&#xff1a; 修改uthread.c&#xff0c;在thread_create函数中新增以下逻辑&#xff1a; 修改uthread.c中的thread_switch函数定义&#xff1a; 修改uthread.c中的th…

绝地求生:看看这些条件,你的四号位队友满足了没有?

这个年头&#xff0c;大家或多或少都有几个固定&#xff08;妹子&#xff09;队友吧 当遇见枪法比较温柔的队友&#xff0c;大家可能会安排Ta去“看屁股”&#xff0c;也就是当四号位。 那究竟什么才是一个天赋型四号位呢&#xff1f; 众所周知&#xff0c;一个好的四号位是最强…

MySQL 表锁问题

MySQL 表锁解决 查看哪些表被锁&#xff0c;字段 In_use 表示有多少线程在使用这张表&#xff0c;字段 name_locked 表示表格是否被锁&#xff0c;0 代表锁定状态 mysql> show OPEN TABLES where In_use > 0; -------------------------------------------------------…

比较 2 名无人机驾驶员:借助分析飞得更高

近年来&#xff0c;越来越多的政府和执法机构使用无人机从空中鸟瞰。为了高效执行任务&#xff0c;无人机必须能够快速机动到预定目标。快速机动使它们能够在复杂的环境中航行&#xff0c;并高效地完成任务。成为认证的无人机驾驶员的要求因国家/地区而异&#xff0c;但都要求您…

Ubuntu 24.04 抢先体验换国内源 清华源 阿里源 中科大源 163源

Update 240307:Ubuntu 24.04 LTS 进入功能冻结期 预计4月25日正式发布。 Ubuntu22.04换源 Ubuntu 24.04重要升级daily版本下载换源步骤 (阿里源)清华源中科大源网易163源 Ubuntu 24.04 LTS&#xff0c;代号 「Noble Numbat」&#xff0c;即将与我们见面&#xff01; Canonica…

Git 版本控制

Git 版本控制 1. About Version Control (关于版本控制)1.1. Local Version Control Systems (本地版本控制系统)1.2. Centralized Version Control Systems (集中化的版本控制系统)1.3. Distributed Version Control Systems (分布式版本控制系统) 2. 换行符的处理3. keyboard…

用xshell7连接服务器,读取后台日志

有时候前端需要读取一些后台日志&#xff0c;比如&#xff0c;有时候接一些验证码啥的 或者有时候前后端不分离时&#xff0c;前端上线项目 先讲一下怎么用密码方式连接服务器 密码方式连接服务器 第一步&#xff0c;安装xshell&#xff0c;在新建会话中填写主机&#xff0…