redis配置类 RedisConfig

package com.menglar.soap.item.common.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.menglar.soap.item.common.listener.KeyExpiredListener;
import org.springframework.beans.factory.annotation.Autowired;
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.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

/**
 * @program: soap-item_v2
 * @description: redis配置类
 * @author: ZhangRiTian
 * @create: 2021-10-25 09:24
 */
@Configuration
public class RedisConfig {

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	/**
	 *监听器连接工厂类
	 */
	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer() {
		RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
		redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
		return redisMessageListenerContainer;
	}

	/**
	 *监听器
	 */
	@Bean
	public KeyExpiredListener keyExpiredListener() {
		return new KeyExpiredListener(this.redisMessageListenerContainer());
	}



@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		// 使用 GenericFastJsonRedisSerializer 替换默认序列化
		GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
		// 设置key和value的序列化规则
		redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
		redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
		// 设置hashKey和hashValue的序列化规则
		redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
		redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
	// 设置支持事物
	redisTemplate.setEnableTransactionSupport(true);
	redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}
}

你可能感兴趣的:(redis,缓存,java)