1. 程式人生 > >redis訊息佇列

redis訊息佇列

spirng配置

<bean id="channelTopic" class="org.springframework.data.redis.listener.ChannelTopic">
	<constructor-arg value="channelTopic" />
</bean>

<bean id="myMessageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
	<constructor-arg>
		<bean class="com.dongnao.MyMessageListener"/>
	</constructor-arg>
</bean>

<bean id="topicContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">
	<property name="connectionFactory" ref="jedisConnFactory" />
	<property name="messageListeners">
		<map>
			<entry key-ref="myMessageListener" value-ref="channelTopic"/>
		</map>
	</property>
</bean>
消費者 監聽
@Slf4j
@Component
public class MyMessageListener implements MessageListener {
   
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
		//處理邏輯
    }
}
生產者
@Component
public class RedisService{

	@Autowired
	private StringRedisTemplate redisTemplate;

	public void sendMessage(String channel, Object message) {
		redisTemplate.convertAndSend(channel,message);
	}
}