RedisTemplateの一般的な使用説明--サブスクリプションの発行

2751 ワード

JAva構成

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                        MessageListenerAdapter listenerAdapter) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.addMessageListener(listenerAdapter, new PatternTopic("testkafka"));
    container.addMessageListener(listenerAdapter, new PatternTopic("testkafka1"));//         
    return container;
}

メッセージリスニングクラス

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

@Component
public class RedisSubscriber extends MessageListenerAdapter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        System.out.println(message);
        //byte[] body = message.getBody();
        //byte[] channel = message.getChannel();
        //String msg = redisTemplate.getStringSerializer().deserialize(body);
        //String topic = redisTemplate.getStringSerializer().deserialize(channel);
       // System.out.println("   topic " + topic + "   :" + msg);
    }

}

シミュレーション生産者

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis     
     * @param data
     * @return
     */
    @GetMapping("/send1")
    String send1(String data) {
        redisTemplate.convertAndSend("testkafka", data);
        return "success";
    }
    /**
     * redis     
     * @param data
     * @return
     */
    @GetMapping("/send2")
    String send2(String data) {
        redisTemplate.convertAndSend("testkafka1", data);
        return "success";
    }

}