我不确定我到底要找什么,但我需要一个类似Keyed Object Pool的东西,但更多的是一个托管的对象集,我传递一个键和对象。Apache池你传递一个键给addObject(K键),工厂创建对象。不是我需要的,因为我已经有了对象。
我的场景是,我有一个Spring Boot 应用程序(ServerApp),其中有许多长期存在的WebSocketSession。WebSockets是来自硬件设备的连接,用于向ServerApp发送状态信息并侦听来自ServerApp的命令。ServerApp可以接受将向设备发送命令的Web服务调用。由于一次只有一个人可以访问设备,因此我需要管理对设备的访问。
控制器使用设备名称从池中查找设备。WebSocketHandler将在连接进入时添加设备:
静止控制器:
// web service call handler
@RequestMapping(value="/sendtocrom",method=RequestMethod.POST,consumes="text/plain")
public Response sentToDevice(
@RequestHeader(value="Authorization") String authorization,
@RequestParam(value="deviceName") String deviceName,
@RequestBody String payload)
{
try {
DeviceWebSocket device = pool.borrowObject(deviceName); //wait for the device to become available
device.getWebSocket().sendMessage(new TextMessage(payload)); //send data to the device via websocket
pool.returnObject(deviceName); //return the device to the pool so other service calls can use it.
return Response(true); //return that message was sent
} catch(NotAvailableException e) {
return Response(false); //return that we were not able to communicate with the device
}
}
Web套接字处理程序:
//when a connection comes in, add it to the pool
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String deviceName = getDeviceName(session); //deviceName passed in through a session header
pool.add(deviceName,session); //add the device to the pool
}
//when something comes in from the websocket, process it, and send a response
@Override
protected void handleTextMessage(WebSocketSession sesssion,TextMessage message) {
String payload = message.getPayload();
String deviceName = getDeviceName(session); //deviceName passed in through a session header}
//process message
try {
//we need to lock the resource before sending incase a web service call is sending something
DeviceWebSocket device = pool.borrowObject(deviceName);
device.getWebSocket().sendMessage(new TextMessage(new Response()));
pool.returnObject(deviceName);
} catch(Exception e) {
//handle error
}
1条答案
按热度按时间eaf3rand1#
据推测,可能有多个发送者在等待他们解锁的机会,或者换句话说排队。
向每个设备连接类/对象添加一个FIFO队列和一个消费者。发送消息时,将其写入队列。当队列消费者处理完前一条消息后,它将拾取新添加的消息并发送。
如果您需要更多的实现细节,请告诉我。