打字稿:类,静态变量,单例

时间:2020-09-10 23:11:28

标签: typescript

你好,我有关于打字稿,静态,单例的问题 我有以下逻辑,我有一个Main类,该类具有Connection作为一个静态变量,并具有一个Channel,该Channel是一个类的实例(并且还必须是静态的,即只是一个通道)。

主要班级:

class Broker {
  static connection: Connection = undefined;
  static channel: BrokerChannel = undefined;
  static urli: string = process.env.RABBIT_URL || 'url';
  private static listenConnectionEvents = (): Promise<Connection> => {
    return new Promise((resolve, reject) => {
      if (!Broker.connection) {
        Broker.urli ? Broker.start() : reject();
        reject();
      }
      resolve(
        Broker.connection.on('error', (err: Error) => {
          logger.error(err.message);
          setTimeout(Broker.start, 10000);
        }) &&
          Broker.connection.on('close', (err: Error) => {
            if (err) {
              logger.error('connection closed because err!');
              setTimeout(Broker.start, 10000);
            }
            logger.info('connection to RabbitQM closed!');
          })
      );
    });
  };
  private static connectRabbitMQ = () => {
    return new Promise<Connection>((resolve, reject) => {
      if (Broker.connection || !Broker.urli) {
        const message = !Broker.urli
          ? 'The host of rabbitmq was not found in the environment variables'
          : 'Connection has already been established';
        logger.info(message);
        reject(new Error(message));
      }
      retry<Connection>(() => connect(Broker.urli), 10, 1000)
        .then((conn) => {
          Broker.connection = conn;
          resolve(Broker.listenConnectionEvents());
        })
        .catch((err) => reject(new Error(err)));
    });
  };
  static start = () => {
    Broker.connectRabbitMQ().catch((error: Error) => {
      throw error;
    });
  };
}
export let ConnectionMQ: Connection = Broker.connection;
export let StartMQ = () => {
  return Broker.start();
};

渠道类别:

import { ConnectionMQ } from './broker';
export class BrokerChannel {
  static Connection: ConnectionMQ = ConnectionMQ
  static queues: IQueue = undefined;
  static exchanges: IExchanges = undefined;
  static channel: Channel = undefined;
  static binds: IBinds = undefined;
  static getChannel = () => {
    return new Promise<Channel>((resolve, reject) => {
      if (BrokerChannel.channel) reject();
      Connection.createChannel().then((ch) => {
        BrokerChannel.channel = ch;
        resolve(BrokerChannel.channel);
      });
    });
  };
}

用法:

export let ConnectionMQ: Connection = Broker.connection;
export let StartMQ = () => {
  return Broker.start();
};
export let ChannelMQ: Channel = BrokerChannel.channel;
export let subscribeQueue = BrokerChannel.subscribeQueue({ queue_name: 'A' });

但是要做到这一点,我需要将所有函数声明为静态,而且我不能拥有构造函数,也不能拥有依赖项注入 我想知道使用它是否可行? 还是在我的用例中,最好创建Main类的Singleton?

像这样:

const server = Broker.getInstance();
server.setChannel(new BrokerChannel(server.getConnection()))

server.channel.subscribeQueue = BrokerChannel.subscribeQueue({ queue_name: 'A' });

我想知道哪个更清洁,更适合我的用例?

我认为,使用第二个选项,我可以注入依赖项,这在第一个选项中是不可能的。

0 个答案:

没有答案