Tk4*_*421 10 python spring stomp rabbitmq spring-websocket
我有一个网站(Java + Spring),它依赖于Websockets(Stomp over Websockets for Spring + RabbitMQ + SockJS)来实现某些功能.
我们正在创建一个基于Python的命令行界面,我们想添加一些使用websockets已经可用的功能.
有谁知道如何使用python客户端,所以我可以使用SockJS协议连接?
PS_我知道一个简单的库,我没有测试,但它没有订阅主题的能力
PS2_因为我可以从python直接连接到RabbitMQ的STOMP并订阅一个主题但直接暴露RabbitMQ感觉不对.有关第二种选择的任何评论?
我使用的解决方案是不使用 SockJS 协议,而是使用“普通的网络套接字”并使用 Python 中的 websockets 包并使用 stomper 包通过它发送 Stomp 消息。stomper 包只生成作为“消息”的字符串,您只需使用 websockets 发送这些消息ws.send(message)
服务器上的 Spring Websockets 配置:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/my-ws-app"); // Note we aren't doing .withSockJS() here
}
}
Run Code Online (Sandbox Code Playgroud)
在代码的 Python 客户端:
import stomper
from websocket import create_connection
ws = create_connection("ws://theservername/my-ws-app")
v = str(random.randint(0, 1000))
sub = stomper.subscribe("/something-to-subscribe-to", v, ack='auto')
ws.send(sub)
while not True:
d = ws.recv()
m = MSG(d)
Run Code Online (Sandbox Code Playgroud)
现在d将是一个 Stomp 格式的消息,它具有非常简单的格式。MSG 是我写的一个快速而肮脏的类来解析它。
class MSG(object):
def __init__(self, msg):
self.msg = msg
sp = self.msg.split("\n")
self.destination = sp[1].split(":")[1]
self.content = sp[2].split(":")[1]
self.subs = sp[3].split(":")[1]
self.id = sp[4].split(":")[1]
self.len = sp[5].split(":")[1]
# sp[6] is just a \n
self.message = ''.join(sp[7:])[0:-1] # take the last part of the message minus the last character which is \00
Run Code Online (Sandbox Code Playgroud)
这不是最完整的解决方案。没有取消订阅,Stomp 订阅的 id 是随机生成的,不会“记住”。但是,stomper 库为您提供了创建取消订阅消息的能力。
服务器端发送的任何内容/something-to-subscribe-to都将被订阅它的所有 Python 客户端接收。
@Controller
public class SomeController {
@Autowired
private SimpMessagingTemplate template;
@Scheduled(fixedDelayString = "1000")
public void blastToClientsHostReport(){
template.convertAndSend("/something-to-subscribe-to", "hello world");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2283 次 |
| 最近记录: |