如何将分离应用于一项服务中的多个任务?
我有一种执行很多事情的服务方法。
public Result DoSomething(){
var queryResult = service.GetResult();
SaveResultToRedis(queryResult);
logger.Log($"this data saved in redis successfully {queryResult.Id}");
AddSomethingToKafka(queryResult);
logger.Log($"this data saved in kafka successfully {queryResult.Id}");
logger.Log($"this data response is success {queryResult.Id}");
}
在此指控中,
- 如果Redis或Kafka失败,请求响应将失败。
- 如果Logger服务失败,请求响应将失败。
- 如果我将所有逻辑放入尝试捕获块中,则代码看起来很糟糕。
在这种说法中可以采用哪种方式?是否有任何设计模式方法?
I have a service method that does so many things.
public Result DoSomething(){
var queryResult = service.GetResult();
SaveResultToRedis(queryResult);
logger.Log(quot;this data saved in redis successfully {queryResult.Id}");
AddSomethingToKafka(queryResult);
logger.Log(quot;this data saved in kafka successfully {queryResult.Id}");
logger.Log(quot;this data response is success {queryResult.Id}");
}
In this stuation,
- if redis or kafka fails, the request response will fail.
- if logger service fails, the request response will fail.
- if I put all logics in try catch blocks, code will appear so bad.
Which way may apply in this stuations? Is there any design pattern approaches or else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想尝试使方法更薄,请尝试应用固体规则。
如果
dosomething()
方法仅将数据保存到某些数据库或事件系统,那么我们可以通过数据库或事件系统将它们分开。但是,代码示例只是在两个地方保存,这不是一个不错的选择,而不是存储。作为一种替代性,可以通过创建一个私人助手方法来隐藏
logger.log
方法,并从dosomething()
::完整的代码看起来像这样:
If you want to try to make your method thinner, then try to apply SOLID rules.
If
DoSomething()
method just saves data to some database or event system, then we can separate them by database or event systems. However, code example just saves in two places and it would not be great choice separate by storage.As an alterantive, it is possible to hide
logger.log
methods by creating a private helper method and call it fromDoSomething()
:and the full code looks like this: