本文共 2774 字,大约阅读时间需要 9 分钟。
当需要在Spring Boot应用中集成Redis时,下面将从基础操作到高级应用全面的介绍如何实现 Redis 与 Spring Boot 的无缝整合。
在项目中首先需要引入相关的 Redis 描述文件。推荐使用Redis客户端 Jedis,具体依赖信息如下:
redis.clients jedis 3.2.0
同时为了充分发挥Spring Boot与Redis的优势,还需引入Spring Boot Redis集成starter包:
org.springframework.boot spring-boot-starter-data-redis
另外,为了支持连接池功能,需引入Apache Commons Pool2:
org.apache.commons commons-pool2
在应用程序启动之前,需要确保Redis服务器认可应用的连接请求。以下是基本的连接代码示例:
Jedis jedis = new Jedis("192.168.181.138", 6379); 那种直接创建 Jedis 实例的方式可以满足基本需求,但建议在商业环境中使用 LettuceConnectionFactory 提供的连接池机制,以享受高效的线程管理和负载均衡能力。
使用 Jedis 或 RedisTemplate 进行 Redis 操作时,常用的方式如下:
操作字符串:
redisTemplate.opsForValue().set("123", "1111111"); 获取字符串值:
String value = redisTemplate.opsForValue().get("123"); 操作Hash:
redisTemplate.opsForHash().hSet("user", "id", "123"); 操作列表:
redisTemplate.opsForList().leftPush("my-list", "new-element"); 操作集合:
redisTemplate.opsForSet().add("my-set", "new-element"); 在Spring Boot项目中整合 Redis,主要通过 RedisTemplate 实现。
@Configurationpublic class RedisConfig { @Bean public RedisTemplate redisTemplate( LettuceConnectionFactory connectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; }} 这里,RedisTemplate 已经配置好了:
StringRedisSerializer。GenericJackson2JsonRedisSerializer 将 Java 对象序列化为 JSON 格式存储。在 application.properties 文件中,设置 Redis 连接信息:
# Redis服务器地址spring.redis.host=192.168.181.138# Redis服务器连接端口spring.redis.port=6379# 连接池最大连接数,默认为8spring.redis.lettuce.pool.max-active=20# 最大阻塞等待时间,默认为-1(无限制)spring.redis.lettuce.pool.max-wait=-1# 最大空闲连接数,默认为8spring.redis.lettuce.pool.max-idle=8# 最小空闲连接数,默认为0spring.redis.lettuce.pool.min-idle=0
这些配置只需在项目启动之前准备好,Spring Boot会自动初始化 Redis 连接池并管理连接。
@Controllerpublic class DemoController { @Autowired private RedisTemplate redisTemplate; @RequestMapping("/home") @ResponseBody public String setRedis() { redisTemplate.opsForValue().set("123", "1111111"); String value = redisTemplate.opsForValue().get("123"); System.out.println("从Redis获取到的值为:" + value); return "从Redis获取到的值为:" + value; }} 这个测试控制器主要展示了如何在Spring Boot应用中进行 Redis 操作,包括:
opsForValue 操作字符串值。opsForHash 操作哈希数据结构。转载地址:http://vdgjz.baihongyu.com/