Проблема Spring Boot Redis Несколько приложений, использующих данные - PullRequest
0 голосов
/ 31 октября 2019

У меня есть два приложения, для которых я использую Spring Boot и Redis. Из обоих приложений я создаю данные для Redis.

ВЫПУСК Данные, полученные с помощью Spring Boot Redis Application 1, недоступны для Redis Application 2 и наоборот.

Redis работает локально.

YAML приложения для обоих приложений одинаков -

spring:
  redis:
    host: localhost
    port: 6379

Класс модели -

@RedisHash(timeToLive = 300,value = "alerts")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RedisModel {

    @Id
    private String id;

    private String message;

    public RedisModel(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "RedisModel{" +
                "id='" + id + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

Есть ли некоторыепараметры, которые пропущены ?? Пожалуйста, дайте мне знать в случае каких-либо вопросов. Spring Boot - версия 2.2.0.

1 Ответ

0 голосов
/ 31 октября 2019

Я думаю, что RedisConfiguration, созданная весенней загрузкой, будет именовать эти ключи кеша с именем вашего приложения. Поэтому они не будут видны друг другу. Чтобы обойти это, вам нужно будет выполнить свою собственную настройку RedisConfiguration и отключить префикс с помощью disableKeyPrefix(), а затем установить собственный префикс с помощью computePrefixWith(...). Вот пример:

    @Bean
    public RedisCacheManager cacheManager( RedisConnectionFactory redisConnectionFactory,
                                           ResourceLoader resourceLoader ) {
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
                .builder( redisConnectionFactory )
                .cacheDefaults( determineConfiguration( resourceLoader.getClassLoader() ) );
        List<String> cacheNames = this.cacheProperties.getCacheNames();
        if ( !cacheNames.isEmpty() ) {
            builder.initialCacheNames( new LinkedHashSet<>( cacheNames ) );
        }
        return builder.build();
    }

    private RedisCacheConfiguration determineConfiguration(
            ClassLoader classLoader ) {
        if ( this.redisCacheConfiguration != null ) {
            return this.redisCacheConfiguration;
        }
        CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
                .modulesToInstall( new SimpleModule().addSerializer( new NullValueSerializer( null ) ) )
                .failOnEmptyBeans( false )
                .build();
        mapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY );

        ObjectMapper mapper = new Jackson2ObjectMapperBuilder()
                .modulesToInstall( new SimpleModule().addSerializer( new NullValueSerializer( null ) ) )
                .failOnEmptyBeans( false )
                .build();
        mapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY );

        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer( mapper );

        //get the mapper b/c they registered some internal modules
        config = config.serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( serializer ) );

        if ( redisProperties.getTimeToLive() != null ) {
            config = config.entryTtl( redisProperties.getTimeToLive() );
        }
        if ( redisProperties.getKeyPrefix() != null ) {
            config = config.prefixKeysWith( redisProperties.getKeyPrefix() );
        }
        if ( !redisProperties.isCacheNullValues() ) {
            config = config.disableCachingNullValues();
        }
        if ( !redisProperties.isUseKeyPrefix() ) {
            config = config.disableKeyPrefix();
            config = config.computePrefixWith( cacheName -> cacheName + "::" );
        }
        return config;
    }
...