第4篇:服务层抽象与复用逻辑
在业务系统复杂度指数级增长的今天,服务层(Service Layer)的合理设计直接影响着系统的可维护性和扩展性。本文将深入剖析 Egg.js 框架中的服务层架构设计,从基础实现到高级封装,全方位讲解企业级应用的开发实践。
一、Service 层核心职责与依赖注入
1. Service 层定位原则
- 数据访问代理:统一管理数据库/第三方API调用
- 业务逻辑容器:封装核心业务流程
- 事务协调中心:管理跨模型操作的事务边界
- 复用基础设施:集成缓存、消息队列等公共服务
2. 依赖注入实现
通过 ctx.service
访问服务实例:
// app/controller/user.js
async create() {const { ctx } = this;// 调用服务层方法const user = await ctx.service.user.createWithProfile(ctx.request.body);ctx.body = user;
}// app/service/user.js
class UserService extends Service {// 注入其他服务get profileService() {return this.ctx.service.profile;}async createWithProfile(data) {const user = await this.createUser(data);await this.profileService.initUserProfile(user.id);return user;}
}
依赖管理规范:
- 禁止服务层之间循环依赖
- 基础服务通过
app.js
挂载到全局 - 敏感服务使用动态加载机制
二、业务逻辑复用模式
1. 基础复用方案
(1) 继承式复用
// app/core/base_service.js
class BaseService extends Service {async softDelete(id) {return this.ctx.model[this.modelName].update({ id }, { deleted_at: new Date() });}
}// app/service/article.js
class ArticleService extends BaseService {get modelName() { return 'Article'; }
}
(2) 组合式复用
// app/core/crud_operations.js
module.exports = {async bulkUpdate(ids, data) {return this.model.update({ id: { [Op.in]: ids } },{ where: data });}
};// app/service/product.js
const CrudOperations = require('../core/crud_operations');class ProductService extends Service {constructor(ctx) {super(ctx);Object.assign(this, CrudOperations);}
}
2. 高级复用模式
(1) 策略模式实现
// app/core/payment_strategies
class AlipayStrategy {async pay(amount) { /* 支付宝实现 */ }
}class WechatPayStrategy {async pay(amount) { /* 微信支付实现 */ }
}// app/service/payment.js
class PaymentService extends Service {async createPayment(type, amount) {const strategy = this.getStrategy(type);return strategy.pay(amount);}getStrategy(type) {const strategies = {alipay: new AlipayStrategy(this.ctx),wechat: new WechatPayStrategy(this.ctx)};return strategies[type];}
}
(2) 管道模式处理
// app/core/pipeline.js
class OrderPipeline {constructor() {this.steps = [];}addStep(step) {this.steps.push(step);}async execute(data) {return this.steps.reduce((promise, step) => promise.then(step),Promise.resolve(data));}
}// 使用示例
const pipeline = new OrderPipeline();
pipeline.addStep(validateStock).addStep(calculatePrice).addStep(createOrder);
await pipeline.execute(orderData);
三、事务处理与数据库封装
1. 自动事务管理
// app/core/transaction.js
module.exports = async function (ctx, fn) {const transaction = await ctx.model.transaction();try {const result = await fn(transaction);await transaction.commit();return result;} catch (err) {await transaction.rollback();throw err;}
};// 使用示例
await ctx.service.transaction(async (t) => {await serviceA.create(dataA, { transaction: t });await serviceB.update(dataB, { transaction: t });
});
优化建议:建立全局的异常捕获机制
2. 数据库操作封装
// app/service/base.js
class BaseService extends Service {async findWithCache(key, queryFn, ttl = 60) {const cache = await this.app.redis.get(key);if (cache) return JSON.parse(cache);const data = await queryFn();await this.app.redis.setex(key, ttl, JSON.stringify(data));return data;}async paginate(model, options) {const { page = 1, pageSize = 15 } = options;const result = await model.findAndCountAll({offset: (page - 1) * pageSize,limit: pageSize,...options});return {data: result.rows,pagination: {page: Number(page),pageSize: Number(pageSize),total: result.count}};}
}
事务最佳实践:
- 单个事务操作不超过5个SQL
- 事务内避免远程HTTP调用
- 使用事务隔离级别控制
- 记录事务日志用于审计
四、服务单元测试策略
1. 测试环境搭建
// test/service/user.test.js
const { app, assert } = require('egg-mock/bootstrap');describe('UserService', () => {let ctx;beforeEach(async () => {ctx = app.mockContext();await app.model.sync({ force: true });});it('should create user with profile', async () => {const service = ctx.service.user;const user = await service.createWithProfile({username: 'test',profile: { bio: 'developer' }});assert(user.id);const profile = await ctx.model.Profile.findOne({where: { userId: user.id }});assert(profile.bio === 'developer');});
});
2. 高级测试技巧
(1) 模拟外部依赖
app.mockService('payment', 'create', () => {return { status: 'success' };
});app.mockClassFunction('redis', 'get', async (key) => {return JSON.stringify({ cached: true });
});
(2) 事务回滚测试
it('should rollback when error occurs', async () => {await assert.rejects(async () => {await ctx.service.transaction(async t => {await createTestData(t);throw new Error('test rollback');});},{ message: 'test rollback' });const count = await ctx.model.Test.count();assert(count === 0);
});
测试覆盖率优化:
- 核心服务保持100%行覆盖
- 使用
nyc
生成覆盖率报告 - 集成SonarQube进行质量检测
- 添加Mutation Test(变异测试)
下篇预告:中间件开发与实战应用
下一篇将深入探讨:
- 中间件执行机制与洋葱模型
- 编写日志/权限/性能监控中间件
- 配置全局与路由级中间件
- 常见中间件开发陷阱规避
核心价值:通过中间件体系提升系统可观测性,降低故障排查时间60%!
架构演进建议
-
服务拆分原则:
- 按业务域垂直拆分
- 公共能力下沉为基类
- 高频变动逻辑独立封装
- 第三方服务代理隔离
-
监控体系建设:
- 服务调用链追踪
- SQL执行时间监控
- 服务依赖关系图谱
- 异常熔断机制
通过合理的服务层设计,可使核心业务代码量减少40%,同时提升系统可维护性。建议根据项目阶段选择适合的复用策略,初期以继承方案为主,复杂阶段采用组合模式,超大型项目可引入领域驱动设计(DDD)。欢迎在评论区留下你遇见的「服务层架构」设计经验与挑战,共同探讨最佳实践!