【spring boot】2.0 redisパブリッシュ購読

2974 ワード

一・導入依存
    
        org.springframework.boot
        spring-boot-starter-data-redis
    

二、配置ファイル
spring:
  redis:
    host: redis
    port: 6379
    timeout: 3000
    password: ""

三・開発
1・redis発行購読構成クラスRedisSubListenerConfig
ListenerAdapterはアダプタを構築し、listenerがメッセージを受信する方法を指定します.RedisMessageListenerContainerはtopicにリスニングアダプタを追加します.
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 *   :
 *
 * @version V1.0
 * @since 2019.4.25
 */
@Configuration
public class RedisSubListenerConfig {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(VideoConstant.TOPIC_VIDEO));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(HandlerService handlerService ) {
        return new MessageListenerAdapter(handlerService , "receive");
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    @Bean
    public RedisTemplate redisTemplateString() {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}

2・HandlerService自己作成実装クラス実装メッセージ対メッセージの処理ロジック
public interface HandlerService {

    /**
     *     
     */
    void receive(String map);

}


3・メッセージの送信
@Autowired
private RedisTemplate redisTemplateString;

redisTemplate.convertAndSend(topic, msg);