耀眼的橘子的gravatar头像
耀眼的橘子 2016-10-21 11:33:44
spring整合websocket,如何在服务端依赖注入service

在websocket 中使用注解式编程中,使用@Autowired 自动注入 service

第一步 :在pom.xml文件中添加  jar 包

             <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-websocket</artifactId>
			<version>4.0.0.RELEASE</version>
		</dependency>

第二步  :在服务端添加configurator = SpringConfigurator.class

package com.chinasofti.eshop.websocket2;

import org.springframework.web.socket.server.standard.SpringConfigurator;

//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。
@ServerEndpoint(value = "/WebSocketServer",configurator = SpringConfigurator.class)
public class WebSocketServer {
	
	@Autowired
	private NoticeService noticeService;

	@OnMessage
	public void incoming(String message) {
		String httpid = this.id;
		System.out.println("httpid" + httpid);
		Notice notice = new Notice();
		notice.setId(UUIDUtils.getUUID());
//		notice.setConsumerId(httpid);
		notice.setConsumerType("1");
		notice.setType("1");
		notice.setTitle("订单消息");
		notice.setContent(message);
		notice.setStartTime(DateTimeUtil.dataToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		notice.setCreateTime(DateTimeUtil.dataToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		notice.setEndTime(DateTimeUtil.dataToString(new Date(), "2017-12-29 23:59:59"));
		notice.setIsDelete("0");
		System.out.println(noticeService);
		noticeService.insert(notice);     //将消息持久化
		
	}

	@OnError
	public void onError(Throwable t) throws Throwable {
		LOGGER.error("Chat  Error: " + t.toString(), t);
	}
	
	//广播
	private static void broadcast(String msg) {
		for (WebSocketServer client : connections) {
			try {
				synchronized (client) {
					client.session.getBasicRemote().sendText(msg);
				}
			} catch (IOException e) {
				LOGGER.debug("Chat Error: 未能发送消息给客户端!", e);
				connections.remove(client);
				try {
					client.session.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				String message = String.format("* %s",  "websocket 已经关闭 .");
				broadcast(message);
			}
		}
	}
}

打赏
最近浏览
十二月终 2021年7月19日
暂无贡献等级
hetao_xiangyu  LV1 2020年8月6日
luomoqq  LV1 2020年3月2日
nextstep  LV11 2020年2月20日
dreafm 2020年2月9日
暂无贡献等级
lmkkkkkkkkkkk  LV1 2019年12月28日
Kongwb 2019年9月10日
暂无贡献等级
小周晴  LV6 2019年7月31日
清风自来  LV3 2019年6月19日
zhuiyunyiye  LV12 2019年4月2日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友