https://www.enterpriseintegrationpatterns.com/patterns/messaging/DynamicRouter.html
我正在努力在 Ballerina 中实现一个中介器,充当传入 HTTP 请求的动态路由器。目标是将这些请求路由到相关的服务端点。我需要在运行时添加新路由并删除现有路由。
Ballerina 是适合这项任务的语言吗?如果是的话,有人可以提供一个基本的代码框架来帮助我开始吗?
让我们想象一个类似食品配送平台的场景,我们称之为“QuickBite Connect”。在此用例中,餐厅动态注册其在不同时间提供食物的可用性。此注册涉及通知调解员他们的存在。
沟通模式涉及餐厅在有空时向调解员发出信号表示其存在,并在不空时宣布退出。现在,当用户通过 QuickBite Connect 下订单时,动态路由器会根据餐厅当前的供应情况将订单定向到相应的餐厅。
import ballerina/http;
type Restaurant readonly & record {|
string restaurantId;
string restaurantUrl;
"AVAILABLE"|"UNAVAILABLE" status;
|};
// store the mapping of <Restaurant Id : Restaurant Url>
isolated map<http:Client> routingTable = {};
service /api/v1/mediator on new http:Listener(8080) {
isolated resource function post placeOrder(http:Request request) returns http:Response|error {
string restaurantId = check request.getHeader("restaurantId");
http:Client? restaurantEp;
lock {
restaurantEp = routingTable[restaurantId];
}
if restaurantEp is () {
return error("restaurant not avaiable for service.");
}
// output channel
return restaurantEp->/placeOrder.post(check request.getJsonPayload());
}
// control channel
resource function post updateStatus(Restaurant restaurant) returns error? {
if restaurant.status == "UNAVAILABLE" {
lock {
_ = routingTable.removeIfHasKey(restaurant.restaurantId);
}
} else {
http:Client cl = check new (restaurant.restaurantUrl);
lock {
routingTable[restaurant.restaurantId] = cl;
}
}
}
}