2026-06-15 15:52:52 +08:00
|
|
|
|
package com.webgame.webgamebackend.common.config;
|
|
|
|
|
|
|
|
|
|
|
|
import org.springframework.context.annotation.Bean;
|
|
|
|
|
|
import org.springframework.context.annotation.Configuration;
|
2026-06-16 16:02:09 +08:00
|
|
|
|
import org.springframework.context.annotation.Primary;
|
2026-06-15 15:52:52 +08:00
|
|
|
|
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
2026-06-16 16:02:09 +08:00
|
|
|
|
import org.springframework.data.redis.core.RedisTemplate;
|
2026-06-15 15:52:52 +08:00
|
|
|
|
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
2026-06-16 16:02:09 +08:00
|
|
|
|
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
2026-06-15 15:52:52 +08:00
|
|
|
|
|
2026-06-16 16:02:09 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* Redis 配置类:序列化方式 + 消息监听容器
|
|
|
|
|
|
*/
|
2026-06-15 15:52:52 +08:00
|
|
|
|
@Configuration
|
|
|
|
|
|
public class RedisConfigurer {
|
2026-06-16 16:02:09 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 配置 RedisTemplate,使用 String 序列化器替代 Java 原生序列化
|
|
|
|
|
|
* <p>
|
|
|
|
|
|
* 不配置此项的话,Spring Boot 默认使用 JdkSerializationRedisSerializer,
|
|
|
|
|
|
* 存入 Redis 的数据会带有 Java 序列化魔数前缀(\xAC\xED\x00\x05),
|
|
|
|
|
|
* 导致人类不可读且无法被其他语言客户端读取。
|
|
|
|
|
|
*/
|
|
|
|
|
|
@Bean
|
|
|
|
|
|
@Primary
|
|
|
|
|
|
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
|
|
|
|
|
|
RedisTemplate<String, String> template = new RedisTemplate<>();
|
|
|
|
|
|
template.setConnectionFactory(redisConnectionFactory);
|
|
|
|
|
|
StringRedisSerializer stringSerializer = new StringRedisSerializer();
|
|
|
|
|
|
template.setKeySerializer(stringSerializer);
|
|
|
|
|
|
template.setValueSerializer(stringSerializer);
|
|
|
|
|
|
template.setHashKeySerializer(stringSerializer);
|
|
|
|
|
|
template.setHashValueSerializer(stringSerializer);
|
|
|
|
|
|
template.afterPropertiesSet();
|
|
|
|
|
|
return template;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-15 15:52:52 +08:00
|
|
|
|
/**
|
|
|
|
|
|
* 创建并配置 Redis 消息监听容器
|
|
|
|
|
|
* 用于实现 Redis 的发布/订阅功能,支持监听特定频道的消息
|
|
|
|
|
|
*
|
|
|
|
|
|
* @param redisConnectionFactory Redis 连接工厂
|
|
|
|
|
|
* @return 配置好的 RedisMessageListenerContainer 实例
|
|
|
|
|
|
*/
|
|
|
|
|
|
@Bean
|
|
|
|
|
|
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
|
|
|
|
|
|
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
|
|
|
|
|
container.setConnectionFactory(redisConnectionFactory);
|
|
|
|
|
|
return container;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|