Spring boot注入多个redisTemplate,并更改默认序列化策略

该博客详细介绍了如何在Spring Boot应用中配置多个RedisTemplate,分别针对不同类型的键值对(String, Long, Integer),并展示了如何更改默认序列化策略为Jackson2JsonRedisSerializer。通过创建配置类RedisConfig,定义了不同的RedisTemplate Bean,并在RedisController中进行测试,展示了Set、Hash和String的操作。" 113089970,10543589,Qt实现Onvif网络配置功能详解,"['Qt开发', 'Onvif协议', '视频监控', '网络设置', '设备管理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、添加maven依赖
        <dependency>
		   <groupId>org.springframework.boot</groupId>
		   <artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
2、配置文件中增加redis连接相关信息
spring.redis.hostName=192.168.0.134
spring.redis.port=6379
spring.redis.database=0
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-2
3、创建一个配置类
package com.example.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisConnectionFactory getConnectionFactory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        logger.info("JedisConnectionFactory bean init success."
<think>嗯,用户想在Maven项目中使用RedisTemplate,我需要详细解释步骤。首先,应该从添加依赖开始。记得Maven项目需要在pom.xml中添加Spring Boot Data Redis的starter依赖。可能还需要版本管理,比如用Spring Boot的parent来管理版本。用户可能不知道具体的依赖坐标,所以我要给出具体的groupId和artifactId,像org.springframework.bootspring-boot-starter-data-redis。 然后,配置Redis连接信息。用户可能需要在application.yml或application.properties里设置host、port、password这些。要提醒他们根据实际环境修改,比如如果Redis在本地,host就是localhost,默认端口6379。如果有密码的话,得加上password字段,否则可能连不上。 接下来是注入和使用RedisTemplate。可能需要先创建一个配置类,用@Configuration注解,然后在里面定义RedisTemplate的Bean,设置key和value的序列化方式,比如使用StringRedisSerializer,避免乱码问题。或者,如果用户使用Spring Boot的自动配置,可能不需要手动配置,但最好还是说明如何自定义配置,因为实际项目中可能需要调整序列化方式。 然后,在Service或Component中通过@Autowired注入RedisTemplate,示范几个基本的操作,比如opsForValue的set和get方法,还有delete操作。代码示例要简洁,用Java代码块展示,这样用户可以直接复制粘贴。 还要注意可能的问题,比如依赖冲突。这时候需要提到用Maven Enforcer Plugin来检测版本冲突,或者使用mvn dependency:tree来查看依赖树,排除冲突的版本。引用之前的参考资料中的[^5]部分,说明如何解决依赖问题。 另外,用户可能会问如何测试Redis连接是否成功,可以建议他们写个简单的测试用例,或者启动应用后检查日志是否有连接错误。可能还需要提到Redis服务器必须运行,否则会报连接超时。 用户可能对RedisTemplate的更多操作感兴趣,比如使用不同的数据结构,如List、Set、Hash等,可以稍微提一下,但主要聚焦在基本使用上。如果有时间的话,可以补充一些高级配置,比如连接池设置,或者使用Lettuce和Jedis的区别,但根据问题,可能不需要深入。 最后,确保步骤清晰,分点说明,每个部分都有对应的代码示例和配置示例。检查是否有遗漏,比如是否忘记说明Redis服务器的安装和运行,但考虑到用户可能已经搭建好环境,可能不需要详细说明。不过还是可以提醒他们确保Redis服务可用。</think>### 如何在Maven项目中使用RedisTemplate #### 1. 添加Maven依赖 在`pom.xml`中添加Spring Data Redis的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>3.1.5</version> <!-- 版本建议与Spring Boot主版本保持一致 --> </dependency> ``` 若需连接池支持,可添加Lettuce或Jedis客户端: ```xml <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` > **注意**:若出现依赖冲突,可使用`mvn dependency:tree`分析依赖关系,或用Maven Enforcer Plugin强制版本统一[^5]。 --- #### 2. 配置Redis连接 在`application.yml`中配置Redis服务器信息: ```yaml spring: redis: host: localhost port: 6379 password: your_password # 若无密码可省略 database: 0 ``` > **提示**:若通过IntelliJ运行项目,可通过`Run -> Edit Configuration`添加Maven运行配置[^1]。 --- #### 3. 定义RedisTemplate Bean 创建配置类定义序列化方式: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` --- #### 4. 使用RedisTemplate操作数据 在Service类中注入使用: ```java @Service public class RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void setValue(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getValue(String key) { return redisTemplate.opsForValue().get(key); } public void deleteKey(String key) { redisTemplate.delete(key); } } ``` --- #### 5. 验证连接 可添加测试用例验证: ```java @SpringBootTest class RedisTest { @Autowired private RedisTemplate<String, Object> redisTemplate; @Test void testConnection() { redisTemplate.opsForValue().set("testKey", "Hello Redis"); Assertions.assertEquals("Hello Redis", redisTemplate.opsForValue().get("testKey")); } } ``` ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值