1.pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketSTMPconfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
//注册STOMP协议的节点(endpoint),并映射指定的url
public void registerStompEndpoints(StompEndpointRegistry registry) {
//注册一个STOMP的endpoint,并指定使用SockJS协议
registry.addEndpoint("/endpointOyzc").setAllowedOrigins("*").withSockJS();
}
@Override
//配置消息代理(Message Broker)
public void configureMessageBroker(MessageBrokerRegistry registry) {
//点对点应配置一个/user消息代理,广播式应配置一个/topic消息代理
registry.enableSimpleBroker("/topic","/user");
//点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
registry.setUserDestinationPrefix("/user");
}
}
3.websocket代码
@Component
@Slf4j
public class WebSocketSTOMPController {
@Autowired
private SimpMessagingTemplate template;
//广播推送消息
@Scheduled(fixedRate = 3000) // 每3秒钟执行一次,需要在 程序入口 @EnableScheduling,及该类添加注解 @Component
public void sendTopicMessage() {
System.out.println("后台广播推送!");
User user=new User();
//user.setUserName("oyzc");
user.setReal_name("testusername123");
user.setAccount("testaccount");
//user.setAge(10);
this.template.convertAndSendToUser("123abc","/queue/getResponse",user);
}
}
3.使用
npm install stompjs
npm install sockjs-client
<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {
data(){
return{
path:"ws://x.x.x.x:8900/test",
socket:""
}
},
mounted(){
this._initwebscoket()
},
methods:{
_initwebscoket(){
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
var socket = new SockJS('http://x.x.x.x:8900/endpointOyzc');
var stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
stompClient.connect({},function(frame){//连接WebSocket服务端
console.log('Connected:' + frame);
//通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
stompClient.subscribe('/user/123abc/queue/getResponse',function(response){
console.log(response)
var code=JSON.parse(response.body);
console.log(code)
//showResponse(code)
});
});
}
}}}
</script>
注意:前端先建立连接后,在调用后端接口出发 发送socket消息。避免造成接收不到消息
网友评论