Nodejs与分子微服务应用程序,如何保持服务器运行

时间:2020-07-24 03:48:42

标签: node.js moleculer

我正在使用带有Molecular的NodeJS,并使用“ npm run dev”来运行该应用程序。当控制台关闭应用程序时,如何将其作为后台服务运行,而在NodeJS中,我使用“ Forever”模块,我可以使用它或任何其他模块来运行该应用程序。

预先感谢

3 个答案:

答案 0 :(得分:0)

docker很好,但是在某些情况下可能会变得过于复杂。 您可以只安装pm2

npm install pm2 -g

然后

pm2启动app.js

启动应用程序,您可以启动许多应用程序。

pm2列表

查看已启动的应用

pm2保存

保存列表

pm2启动

确保它将在重启后启动您的应用程序

答案 1 :(得分:0)

您可以将项目作为守护程序docker容器运行

答案 2 :(得分:0)

假设您在services目录中拥有所有服务(可以是一项或多项)。

创建一个Moleculer Runner帮助程序脚本,以帮助将应用程序作为Moleculer Project运行。

  • 创建一个moleculer.config.js并将其放置在应用程序的根目录中。
  • package.json文件中添加脚本
    • "dev": "moleculer-runner --repl --hot services/**/*.service.js"
    • "start": "moleculer-runner --instances=max services"

样本 moleculer.config.js

"use strict";

module.exports = {
  // Namespace of nodes to segment your nodes on the same network.
  namespace: "MyMicroService",
  // Unique node identifier. Must be unique in a namespace.
  nodeID: "node@my-machine",
  // Custom metadata store. Store here what you want. Accessing: `this.broker.metadata`
  metadata: {},

  // Enable/disable logging or use custom logger. More info: https://moleculer.services/docs/0.14/logging.html
  // Available logger types: "Console", "File", "Pino", "Winston", "Bunyan", "debug", "Log4js", "Datadog"
  logger: {
    type: "Console",
    options: {
      // Using colors on the output
      colors: true,
      // Print module names with different colors (like docker-compose for containers)
      moduleColors: false,
      // Line formatter. It can be "json", "short", "simple", "full", a `Function` or a template string like "{timestamp} {level} {nodeID}/{mod}: {msg}"
      formatter: "full",
      // Custom object printer. If not defined, it uses the `util.inspect` method.
      objectPrinter: null,
      // Auto-padding the module name in order to messages begin at the same column.
      autoPadding: false,
    },
  },
  // Default log level for built-in console logger. It can be overwritten in logger options above.
  // Available values: trace, debug, info, warn, error, fatal
  logLevel: "info",

  // Define transporter.
  // More info: https://moleculer.services/docs/0.14/networking.html
  // Note: During the development, you don't need to define it because all services will be loaded locally.
  // In production you can set it via `TRANSPORTER=nats://localhost:4222` environment variable.
  transporter: null, //"NATS"
  //   transporter: "NATS", //"null"

  // Define a cacher.
  // More info: https://moleculer.services/docs/0.14/caching.html
  cacher: null,

  // Define a serializer.
  // Available values: "JSON", "Avro", "ProtoBuf", "MsgPack", "Notepack", "Thrift".
  // More info: https://moleculer.services/docs/0.14/networking.html#Serialization
  serializer: "JSON",

  // Number of milliseconds to wait before reject a request with a RequestTimeout error. Disabled: 0
  requestTimeout: 10 * 1000,

  // Retry policy settings. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Retry
  retryPolicy: {
    // Enable feature
    enabled: false,
    // Count of retries
    retries: 5,
    // First delay in milliseconds.
    delay: 100,
    // Maximum delay in milliseconds.
    maxDelay: 1000,
    // Backoff factor for delay. 2 means exponential backoff.
    factor: 2,
    // A function to check failed requests.
    check: (err) => err && !!err.retryable,
  },

  // Limit of calling level. If it reaches the limit, broker will throw an MaxCallLevelError error. (Infinite loop protection)
  maxCallLevel: 100,

  // Number of seconds to send heartbeat packet to other nodes.
  heartbeatInterval: 10,
  // Number of seconds to wait before setting node to unavailable status.
  heartbeatTimeout: 30,

  // Cloning the params of context if enabled. High performance impact, use it with caution!
  contextParamsCloning: false,

  // Tracking requests and waiting for running requests before shuting down. More info: https://moleculer.services/docs/0.14/context.html#Context-tracking
  tracking: {
    // Enable feature
    enabled: false,
    // Number of milliseconds to wait before shuting down the process.
    shutdownTimeout: 5000,
  },

  // Disable built-in request & emit balancer. (Transporter must support it, as well.). More info: https://moleculer.services/docs/0.14/networking.html#Disabled-balancer
  disableBalancer: false,

  // Settings of Service Registry. More info: https://moleculer.services/docs/0.14/registry.html
  registry: {
    // Define balancing strategy. More info: https://moleculer.services/docs/0.14/balancing.html
    // Available values: "RoundRobin", "Random", "CpuUsage", "Latency", "Shard"
    strategy: "RoundRobin",
    // Enable local action call preferring. Always call the local action instance if available.
    preferLocal: true,
  },

  // Settings of Circuit Breaker. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Circuit-Breaker
  circuitBreaker: {
    // Enable feature
    enabled: false,
    // Threshold value. 0.5 means that 50% should be failed for tripping.
    threshold: 0.5,
    // Minimum request count. Below it, CB does not trip.
    minRequestCount: 20,
    // Number of seconds for time window.
    windowTime: 60,
    // Number of milliseconds to switch from open to half-open state
    halfOpenTime: 10 * 1000,
    // A function to check failed requests.
    check: (err) => err && err.code >= 500,
  },

  // Settings of bulkhead feature. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Bulkhead
  bulkhead: {
    // Enable feature.
    enabled: false,
    // Maximum concurrent executions.
    concurrency: 10,
    // Maximum size of queue
    maxQueueSize: 100,
  },

  // Enable action & event parameter validation. More info: https://moleculer.services/docs/0.14/validating.html
  validator: true,

  errorHandler: null,

  // Enable/disable built-in metrics function. More info: https://moleculer.services/docs/0.14/metrics.html
  metrics: {
    enabled: false,
    // Available built-in reporters: "Console", "CSV", "Event", "Prometheus", "Datadog", "StatsD"
    reporter: {
      type: "Prometheus",
      options: {
        // HTTP port
        port: 3030,
        // HTTP URL path
        path: "/metrics",
        // Default labels which are appended to all metrics labels
        defaultLabels: (registry) => ({
          namespace: registry.broker.namespace,
          nodeID: registry.broker.nodeID,
        }),
      },
    },
  },

  // Enable built-in tracing function. More info: https://moleculer.services/docs/0.14/tracing.html
  tracing: {
    enabled: false,
    // Available built-in exporters: "Console", "Datadog", "Event", "EventLegacy", "Jaeger", "Zipkin"
    exporter: {
      type: "Console", // Console exporter is only for development!
      options: {
        // Custom logger
        logger: null,
        // Using colors
        colors: true,
        // Width of row
        width: 100,
        // Gauge width in the row
        gaugeWidth: 40,
      },
    },
  },

  // Register custom middlewares
  middlewares: [],

  // Register custom REPL commands.
  replCommands: null,

  // Called after broker created.
  created(broker) {},

  // Called after broker started.
  async started(broker) {},

  // Called after broker stopped.
  async stopped(broker) {},
};