Added push messages using the @Scheduled annotation.
This commit is contained in:
parent
6dab1d510f
commit
18954efcee
@ -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>
|
||||
|
@ -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);
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user