44 lines
1.8 KiB
Java
44 lines
1.8 KiB
Java
package com.dongni.collisionavoidance.webSocket.cache;
|
||
|
||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||
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.serializer.GenericJackson2JsonRedisSerializer;
|
||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||
|
||
/**
|
||
* WebSocket消息缓存配置
|
||
* 配置Redis用于缓存WebSocket消息,支持重连恢复
|
||
*/
|
||
@Configuration
|
||
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true", matchIfMissing = true)
|
||
public class CacheConfig {
|
||
|
||
/**
|
||
* 配置RedisTemplate用于WebSocket消息缓存
|
||
* @param connectionFactory Redis连接工厂
|
||
* @return 配置好的RedisTemplate
|
||
*/
|
||
@Bean
|
||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
|
||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||
template.setConnectionFactory(connectionFactory);
|
||
|
||
// 使用String序列化器处理key
|
||
template.setKeySerializer(new StringRedisSerializer());
|
||
template.setHashKeySerializer(new StringRedisSerializer());
|
||
|
||
// 使用JSON序列化器处理value,支持WebSocketMessage对象序列化
|
||
GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer();
|
||
template.setValueSerializer(jsonSerializer);
|
||
template.setHashValueSerializer(jsonSerializer);
|
||
|
||
// 启用事务支持
|
||
template.setEnableTransactionSupport(true);
|
||
|
||
template.afterPropertiesSet();
|
||
return template;
|
||
}
|
||
} |