我在后端使用moleculerjs来处理微服务,并且使用其中一个前端应用程序来处理套接字上的通信。为了做到这一点,我使用了moleculer.io。我遇到的问题是,即使我将套接字附加到onBeforeCall()钩子中的ctx,当我在控制器函数中console.log ctx时,套接字也不在那里。
我的网关如下所示(请注意,套接字正被添加到onBeforeCall()挂钩中的ctx对象:
const SocketIOService = require("moleculer-io");
module.exports = {
name: 'oas',
mixins: [SocketIOService],
settings: {
port: 5000,
io: {
namespaces: {
'/': {
events: {
'call': {
aliases: {
'auth.register': 'oas.controllers.auth.register'
},
whitelist: [
'**',
],
onBeforeCall: async function(ctx, socket, action, params, callOptions) { // before hook
console.log('socket: ', socket); // This exists here
ctx.socket = socket; // Here I attach the socket to the ctx object
},
onAfterCall: async function(ctx, socket, res) { // after hook
// console.log('after hook', res)
// res: The response data.
}
}
}
}
}
},
events: {},
actions: {}
}
};我的auth.service看起来是这样的-注意尝试访问ctx.socket的register()函数
"use strict";
/**
* @typedef {import('moleculer').Context} Context Moleculer's Context
*/
module.exports = {
name: "oas.controllers.auth",
/**
* Settings
*/
settings: {
},
/**
* Dependencies
*/
dependencies: [],
/**
* Actions
*/
actions: {
async register(ctx) {
console.log('ctx.socket: ', ctx.socket); // This is undefined
// Other code...
},
/**
* Events
*/
events: {
},
/**
* Methods
*/
methods: {
},
/**
* Service created lifecycle event handler
*/
created() {
},
/**
* Service started lifecycle event handler
*/
async started() {
},
/**
* Service stopped lifecycle event handler
*/
async stopped() {
}
};在这里,在调用的register()函数中,ctx.socket是undefined。这里我漏掉了什么?我假设onBeforeCall()就是为这种目的而设计的,但也许我误解了什么。
有没有不同的方法来确保套接字在被调用的函数中可用?为了澄清,套接字在onBeforeCall()钩子中可用。我需要弄清楚如何让它在未来可用。
发布于 2021-02-12 22:26:13
最后我找到了一种方法来做到这一点。正如@Icebob指出的那样,我不能直接将套接字附加到ctx,而是能够将其附加到ctx.meta,如下所示:
onBeforeCall: async function(ctx, socket, action, params, callOptions) { // before hook
ctx.meta.socket = socket;
},通过这样做,我能够在我的register()函数中成功地访问套接字。
发布于 2021-02-12 22:01:24
你不能这么做。您不能将任何内容放入ctx。ServiceBroker将只序列化和传输ctx.params和ctx.meta属性。但是您不能将套接字放入其中,因为您喜欢的套接字对象是不可序列化的,因此您不能在远程服务中访问它。它可以在整体项目中工作,而不是在微服务项目中工作。
https://stackoverflow.com/questions/66172801
复制相似问题