E-commerce social platform source code please add penguin beg: three five six two forty-seven fifty-nine
Preparation stage
- To install Redis, refer to my other article
- Java 1.8
- Maven 3.0
- idea
Environment depends on
Create a new Springboot project and add the spring-boot-starter-data-redis dependency to its POM file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Copy the code
Create a message receiver
The REcevier class, which is a normal class, needs to be injected into SpringBoot.
public class Receiver {
private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
private CountDownLatch latch;
@Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
}
public void receiveMessage(String message) {
LOGGER.info("Received <" + message + ">"); latch.countDown(); }}Copy the code
Inject message receiver
@Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
}
@Bean
CountDownLatch latch() {
return new CountDownLatch(1);
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}Copy the code
Inject the message listening container
In Spring Data Redis, you need three things to send and receive a message using Redis:
- A connection factory
- A message listening container
- Redis template
Steps 1 and 3 above are done, so just inject the message listening container:
@Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}Copy the code
test
The main method in the springboot entry:
public static void main(String[] args) throws Exception{
ApplicationContext ctx = SpringApplication.run(SpringbootRedisApplication.class, args);
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
CountDownLatch latch = ctx.getBean(CountDownLatch.class);
LOGGER.info("Sending message...");
template.convertAndSend("chat"."Hello from Redis!");
latch.await();
System.exit(0);
}Copy the code
E-commerce social platform source code please add penguin beg: three five six two forty-seven fifty-nine