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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lichuangcsdn/article/details/80866253
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.");
        return factory;
    }

    @Bean
    public RedisTemplate<?, ?> getRedisTemplate(){
        RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory()); //只能对字符串的键值操作
        System.out.println("生成<?,?>template:" + template);
        return template;
    }
    
    @Bean(name = "LongRedisTemplate")
    public RedisTemplate<String, Long> getRedisTemplate1(){
        RedisTemplate<String,Long> template = new RedisTemplate<String,Long>(); //只能对字符串的键值操作
        template.setConnectionFactory(getConnectionFactory());
    
     // 使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        
        System.out.println("生成<String, Long>template:" + template);
        return template;
    }
    
    @Bean(name = "StringRedisTemplate")
    public RedisTemplate<String, String> getRedisTemplate2(){
        RedisTemplate<String,String> template = new RedisTemplate<String,String>(); //只能对字符串的键值操作
        template.setConnectionFactory(getConnectionFactory());
        
        // 使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        
        System.out.println("生成<String, String>template:" + template);
        return template;
    }
    
    @Bean(name = "IntegerRedisTemplate")
    public RedisTemplate<String, Integer> getRedisTemplate3(){
        RedisTemplate<String,Integer> template = new RedisTemplate<String,Integer>(); //只能对字符串的键值操作
        template.setConnectionFactory(getConnectionFactory());
    
     // 使用Jackson2JsonRedisSerialize 替换默认序列化(默认采用的是JDK序列化)
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        
        System.out.println("生成<String,Integer>template:" + template);
        return template;
    }
}
4、使用及测试
A、测试注入不同类型的模板根据 @Resource 注解
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {
	
	@Resource(name = "StringRedisTemplate")
	private RedisTemplate<String, String> stringRedisTemplate;
	
	@Resource(name = "LongRedisTemplate")
	private RedisTemplate<String, Long> longRedisTemplate;
	
	@Resource(name = "IntegerRedisTemplate")
	private RedisTemplate<String, Integer> integerRedisTemplate;
	
	@RequestMapping(value = "/redis")
	public String testRedis() {
		System.out.println("stringRedisTemplate:" + stringRedisTemplate);
		System.out.println("longRedisTemplate:" + longRedisTemplate);
		System.out.println("integerRedisTemplate:" + integerRedisTemplate);
		testStringRedis();
		testLongRedis();
		testIntegerRedis();
		return "成功!";
	}
	
	private void testStringRedis() {
		SetOperations<String, String> set = stringRedisTemplate.opsForSet(); //保存Set
		set.add("set1","22");  
		set.add("set1","33");  
		set.add("set1","33");  
		Set<String> resultSet =stringRedisTemplate.opsForSet().members("set1"); //获取Set
		System.out.println("resultSet:"+resultSet); 
	}
	
	private void testLongRedis() {
		SetOperations<String, Long> set = longRedisTemplate.opsForSet();
		set.add("set2",22L);  
		set.add("set2",22L);  
		set.add("set2",23L);  
		Set<Long> resultSet =longRedisTemplate.opsForSet().members("set2");  
		System.out.println("resultSet:"+resultSet); 
	}
	
	private void testIntegerRedis() {
		SetOperations<String, Integer> set = integerRedisTemplate.opsForSet();
		set.add("set3",222);  
		set.add("set3",333);  
		set.add("set3",555);  
		Set<Integer> resultSet =integerRedisTemplate.opsForSet().members("set3");  
		System.out.println("resultSet:"+resultSet); 
	}
	
}
B、测试例子(测试)Set、Hash、String
        @Resource(name = "IntegerRedisTemplate")
	private RedisTemplate<String, Integer> integerRedisTemplate;
	
	@RequestMapping(value = "/redis")
	public String testRedis() {
		testIntegerSetRedis();
		testIntegerMapRedis();
		testIntegerValueRedis();
		return "成功!";
	}
	
	private void testIntegerSetRedis() {
		System.out.println();
		System.out.println("测试Set结构");
		SetOperations<String, Integer> set = integerRedisTemplate.opsForSet(); //添加Set
		set.add("set1",22);  
		set.add("set1",33);
		set.add("set1",55);  
		Set<Integer> resultSet1 =integerRedisTemplate.opsForSet().members("set1"); //获取Set
		Set<Integer> resultSet5 =integerRedisTemplate.opsForSet().members("set100"); //获取为空的情况
		System.out.println("resultSet5:"+resultSet5); 
		System.out.println("resultSet1:"+resultSet1); 
		set.remove("set1", 22); //删除元素
		Set<Integer> resultSet2 =integerRedisTemplate.opsForSet().members("set1"); //获取Set
		System.out.println("删除后:resultSet2:"+resultSet2);
	}
	
	private void testIntegerMapRedis() {
		System.out.println();
		System.out.println("测试Hash结构");
		HashOperations<String,Object,Object> redisMap = integerRedisTemplate.opsForHash(); //添加Map
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("goodsId", 12345);
		map.put("shopId", 52341);
		map.put("coupon", 3232);
		redisMap.putAll("hashMapTest", map); 
		Map<Object, Object> resultSet1 =integerRedisTemplate.opsForHash().entries("hashMapTest"); //获取Map
		System.out.println("resultSet1:"+resultSet1); 
		redisMap.delete("hashMapTest", "goodsId"); //删除key
		Map<Object, Object> resultSet2 =integerRedisTemplate.opsForHash().entries("hashMapTest"); //获取Map
		System.out.println("删除后:resultSet2:"+resultSet2); 
	}
	
	private void testIntegerValueRedis() {
		System.out.println();
		System.out.println("测试String-ValueOperations结构");
		ValueOperations<String, Integer> redisValue1 = integerRedisTemplate.opsForValue();
		redisValue1.set("abcde", 123444); //设置
		Integer result1 = redisValue1.get("abcde"); //获取
		System.out.println("result:" + result1);
		
		BoundValueOperations<String, Integer> redisValue2 = integerRedisTemplate.boundValueOps("abcde");
		redisValue2.set(6666); //设置
		Integer result2 = redisValue2.get(); //获取
		System.out.println("result:" + result2);
		integerRedisTemplate.delete("abcde");
		BoundValueOperations<String, Integer> redisValu3 = integerRedisTemplate.boundValueOps("abcde");
		System.out.println("删除后:result3:" + redisValu3.get());
	}
控制台打印结果:
测试Set结构
resultSet5:[]
resultSet1:[22, 33, 55]
删除后:resultSet2:[33, 55]

测试Hash结构
resultSet1:{goodsId=12345, coupon=3232, shopId=52341}
删除后:resultSet2:{shopId=52341, coupon=3232}

测试String-ValueOperations结构
result:123444
result:6666
删除后:result3:null

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭