SpringBoot怎么整合Redis实现热点数据缓存
我们以IDEA SpringBoot作为 Java中整合Redis的使用 的测试环境
首先,我们需要导入Redis的maven依赖
<!-- Redis的maven依赖包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
其次,我们需要在配置文件中配置你的Redis配置信息,我使用的是 .yml文件格式
# redis配置 spring: redis: # r服务器地址 host: 127.0.0.1 # 服务器端口 port: 6379 # 数据库索引(默认0) database: 0 # 连接超时时间(毫秒) timeout: 10s jedis: pool: # 连接池中的最大空闲连接数 max-idle: 8 # 连接池中的最小空闲连接数 min-idle: 0 # 连接池最大连接数(使用负值表示没有限制) max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1
对 redis 做自定义配置
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfigurer extends CachingConfigurerSupport { /** * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 */ @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) { // 配置redisTemplate RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); // 设置序列化 Jackson2JsonRedisSerializer<Object> redisSerializer = getRedisSerializer(); // key序列化 redisTemplate.setKeySerializer(new StringRedisSerializer()); // value序列化 redisTemplate.setValueSerializer(redisSerializer); // Hash key序列化 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // Hash value序列化 redisTemplate.setHashValueSerializer(redisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 设置Jackson序列化 */ private Jackson2JsonRedisSerializer<Object> getRedisSerializer() { Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); redisSerializer.setObjectMapper(om); return redisSerializer; } }
然后,我们需要创建一个RedisUtil来对Redis数据库进行操作
package com.zyxx.test.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; /** * @ClassName RedisUtil * @Author * @Date 2019-08-03 17:29:29 * @Version 1.0 **/ @Component public class RedisUtil { @Autowired private RedisTemplate<String, String> template; /** * 读取数据 * * @param key * @return */ public String get(final String key) { return template.opsForValue().get(key); } /** * 写入数据 */ public boolean set(final String key, String value) { boolean res = false; try { template.opsForValue().set(key, value); res = true; } catch (Exception e) { e.printStackTrace(); } return res; } /** * 根据key更新数据 */ public boolean update(final String key, String value) { boolean res = false; try { template.opsForValue().getAndSet(key, value); res = true; } catch (Exception e) { e.printStackTrace(); } return res; } /** * 根据key删除数据 */ public boolean del(final String key) { boolean res = false; try { template.delete(key); res = true; } catch (Exception e) { e.printStackTrace(); } return res; } /** * 是否存在key */ public boolean hasKey(final String key) { boolean res = false; try { res = template.hasKey(key); } catch (Exception e) { e.printStackTrace(); } return res; } /** * 给指定的key设置存活时间 * 默认为-1,表示永久不失效 */ public boolean setExpire(final String key, long seconds) { boolean res = false; try { if (0 < seconds) { res = template.expire(key, seconds, TimeUnit.SECONDS); } } catch (Exception e) { e.printStackTrace(); } return res; } /** * 获取指定key的剩余存活时间 * 默认为-1,表示永久不失效,-2表示该key不存在 */ public long getExpire(final String key) { long res = 0; try { res = template.getExpire(key, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } return res; } /** * 移除指定key的有效时间 * 当key的有效时间为-1即永久不失效和当key不存在时返回false,否则返回true */ public boolean persist(final String key) { boolean res = false; try { res = template.persist(key); } catch (Exception e) { e.printStackTrace(); } return res; } }
最后,我们可以使用单元测试来检测我们在RedisUtil中写的操作Redis数据库的方法
package com.zyxx.test; import com.zyxx.test.utils.RedisUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class) @SpringBootTest public class TestApplicationTest { @Resource private RedisUtil redisUtil; @Test public void setRedis() { boolean res = redisUtil.set("jay", "周杰伦 - 《以父之名》"); System.out.println(res); } @Test public void getRedis() { String res = redisUtil.get("jay"); System.out.println(res); } @Test public void updateRedis() { boolean res = redisUtil.update("jay", "周杰伦 - 《夜的第七章》"); System.out.println(res); } @Test public void delRedis() { boolean res = redisUtil.del("jay"); System.out.println(res); } @Test public void hasKey() { boolean res = redisUtil.hasKey("jay"); System.out.println(res); } @Test public void expire() { boolean res = redisUtil.setExpire("jay", 100); System.out.println(res); } @Test public void getExpire() { long res = redisUtil.getExpire("jay"); System.out.println(res); } @Test public void persist() { boolean res = redisUtil.persist("jay"); System.out.println(res); } }
建议使用redis-desktop-manager作为Redis数据库中数据的显示工具
至此,我们在日常项目中整合Redis的基本使用操作就完成了,但在实际项目中,可能会涉及到更复杂的用法,可以根据你的业务需求调整Redis的使用即可。
以上是SpringBoot怎么整合Redis实现热点数据缓存的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Redis集群模式通过分片将Redis实例部署到多个服务器,提高可扩展性和可用性。搭建步骤如下:创建奇数个Redis实例,端口不同;创建3个sentinel实例,监控Redis实例并进行故障转移;配置sentinel配置文件,添加监控Redis实例信息和故障转移设置;配置Redis实例配置文件,启用集群模式并指定集群信息文件路径;创建nodes.conf文件,包含各Redis实例的信息;启动集群,执行create命令创建集群并指定副本数量;登录集群执行CLUSTER INFO命令验证集群状态;使

Redis 使用哈希表存储数据,支持字符串、列表、哈希表、集合和有序集合等数据结构。Redis 通过快照 (RDB) 和追加只写 (AOF) 机制持久化数据。Redis 使用主从复制来提高数据可用性。Redis 使用单线程事件循环处理连接和命令,保证数据原子性和一致性。Redis 为键设置过期时间,并使用 lazy 删除机制删除过期键。

解决redis-server找不到问题的步骤:检查安装,确保已正确安装Redis;设置环境变量REDIS_HOST和REDIS_PORT;启动Redis服务器redis-server;检查服务器是否运行redis-cli ping。

要查看 Redis 中的所有键,共有三种方法:使用 KEYS 命令返回所有匹配指定模式的键;使用 SCAN 命令迭代键并返回一组键;使用 INFO 命令获取键的总数。

要从 Redis 读取队列,需要获取队列名称、使用 LPOP 命令读取元素,并处理空队列。具体步骤如下:获取队列名称:以 "queue:" 前缀命名,如 "queue:my-queue"。使用 LPOP 命令:从队列头部弹出元素并返回其值,如 LPOP queue:my-queue。处理空队列:如果队列为空,LPOP 返回 nil,可先检查队列是否存在再读取元素。

启动 Redis 服务器的步骤包括:根据操作系统安装 Redis。通过 redis-server(Linux/macOS)或 redis-server.exe(Windows)启动 Redis 服务。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令检查服务状态。使用 Redis 客户端,如 redis-cli、Python 或 Node.js,访问服务器。

理解 Redis 源码的最佳方法是逐步进行:熟悉 Redis 基础知识。选择一个特定的模块或功能作为起点。从模块或功能的入口点开始,逐行查看代码。通过函数调用链查看代码。熟悉 Redis 使用的底层数据结构。识别 Redis 使用的算法。

使用Redis进行锁操作需要通过SETNX命令获取锁,然后使用EXPIRE命令设置过期时间。具体步骤为:(1) 使用SETNX命令尝试设置一个键值对;(2) 使用EXPIRE命令为锁设置过期时间;(3) 当不再需要锁时,使用DEL命令删除该锁。
