微服务moleculer03

  1. Moleculer 目前支持SQLite,MySQL,MariaDB,PostgreSQL,MSSQL等数据库,这里以mysql为例

  2. package.json 增加mysql依赖

复制代码
"mysql2": "^2.3.3",
"sequelize": "^6.21.3",
"moleculer-db-adapter-sequelize": "^0.2.15",
"moleculer-db": "^0.8.24",
复制代码
npm install moleculer-db-adapter-sequelize sequelize --save
npm install moleculer-db --save

3.然后执行对应数据库的命令

复制代码
SQLite
 npm install sqlite3 --save

# For MySQL
npm install mysql2 --save

# For MariaDB
npm install mariadb --save

# For PostgreSQL
 npm install pg pg-hstore --save

# For MSSQL
$npm install tedious --save
复制代码
4.服务增加如下操作:
复制代码
const { ServiceBroker } = require("moleculer");
const DbService = require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");
const Sequelize = require("sequelize");
const broker = new ServiceBroker();
/**
 * @typedef {import('moleculer').ServiceSchema} ServiceSchema Moleculer's Service Schema
 * @typedef {import('moleculer').Context} Context Moleculer's Context
 */

broker.createService({
	name: "products",
	mixins: [DbService],
	adapter: new SqlAdapter('test', 'root', 'root', {
		host: 'localhost',
		dialect: 'mysql' ,
		pool: {
			max: 5,
			min: 0,
			idle: 10000
		}
	}),
	model: {
		name: "products",
		define: {
			title: Sequelize.STRING,
			content: Sequelize.TEXT,
			votes: Sequelize.INTEGER,
			author: Sequelize.INTEGER,
			status: Sequelize.BOOLEAN
		},
		options: {

		}
	},
});


broker.start()
	// Create a new post
	.then(() => broker.call("products.create", {
		title: "My first post",
		content: "Lorem ipsum...",
		votes: 0
	}))
	.then(() => broker.call("products.find").then(console.log));
复制代码
5.启动项目: 数据库自动创表products,并插入了一条数据,可以查询出来

6.具体的crud 可以参考Sequelize | Feature-rich ORM for modern TypeScript & JavaScript 实现,这里就不详细介绍了

相关推荐
北亚数据恢复10 分钟前
虚拟机数据恢复—ESXi虚拟机下SqlServer数据库数据恢复案例
数据库
susu108301891116 分钟前
使用navicat创建事件event报错You have an error in your SQL syntax
数据库·sql
水力魔方17 分钟前
武理排水管网模拟分析系统应用专题5:模型克隆与并行计算
数据库·c++·算法·swmm
cike_y18 分钟前
Spring-Bean的作用域&Bean的自动装配
java·开发语言·数据库·spring
stella·1 小时前
mysql的时区问题
数据库·mysql·timezone·时区
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vueOA工程项目管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
wang6021252182 小时前
阿里云存储的下载验证
数据库·阿里云·fastapi
独自破碎E2 小时前
Spring Boot工程启动以后,怎么将数据库中已有的固定内容打入到Redis缓存中?
数据库·spring boot·缓存
策知道3 小时前
从“抗旱保苗”到“修渠引水”:读懂五年财政政策的变奏曲
大数据·数据库·人工智能·搜索引擎·政务
深圳市恒星物联科技有限公司3 小时前
恒星物联亮相湖南城市生命线安全工程培训会展会
大数据·数据库·物联网