Spring boot integrates Redis to realize message queue publish subscription

Article directory


Redis has its own message queue with publish subscription mode. You only need to integrate redis in spring boot and listen to the topic.
Redis publish subscription

Integrated Redis

Introducing dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Configure RedisTemplate

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // Set Key to use String serialization
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

Subscription listening class

Subscriber

public class SubscribeListener implements MessageListener {
    /**
     * Subscriptions receive messages from publishers
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // The cached message is serialized and needs to be deserialized. However, new String() can be deserialized, but static method valueOf() cannot.
        System.out.println(new String(pattern) + "Theme release:" + new String(message.getBody()));
    }
}

Publisher

@Component
public class PublishService {
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * Publishing method
     * @param channel Message publishing subscription topic
     * @param message Message information
     */
    public void publish(String channel, Object message) {
        // connection.publish(rawChannel, rawMessage) encapsulated by this method;
        redisTemplate.convertAndSend(channel, message);
    }
}

Add listening topic

Configure listening test topic topic topic in RedisConfig

 @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // Add subscriber listening classes. The number is unlimited. PatternTopic defines listening topics. Here, listening to test topic topics
        container.addMessageListener(new SubscribeListener(), new PatternTopic("test-topic"));
        return container;
    }

Publish and subscribe test

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisMqPsApplicationTests {
    @Autowired
    private PublishService service;

    @Test
    public void contextLoads() {
        for (int i = 0; i < 10; i++) {
            service.publish("test-topic", "hello~~~" + i);
        }
    }

}

Keywords: Redis Spring

Added by aussieguy on Wed, 16 Oct 2019 21:28:50 +0300