Added push messages using the @Scheduled annotation.

This commit is contained in:
Philippe Soares 2020-10-25 23:52:08 -04:00
parent 6dab1d510f
commit 18954efcee
3 changed files with 38 additions and 0 deletions

View File

@ -18,6 +18,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>

View File

@ -3,8 +3,10 @@ package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringBootApp extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);

View File

@ -0,0 +1,31 @@
package com.baeldung.websockets;
import com.github.javafaker.Faker;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
public class ScheduledPushMessages {
private final SimpMessagingTemplate simpMessagingTemplate;
private final Faker faker;
public ScheduledPushMessages(SimpMessagingTemplate simpMessagingTemplate) {
this.simpMessagingTemplate = simpMessagingTemplate;
faker = new Faker();
}
@Scheduled(fixedRate = 5000)
public void sendMessage() {
final String time = new SimpleDateFormat("HH:mm").format(new Date());
simpMessagingTemplate.convertAndSend("/topic/messages",
new OutputMessage("Chuck Norris", faker.chuckNorris().fact(), time));
}
}