感谢Andy Brown 确认我这样做并不是完全疯了。对于任何感兴趣的人来说,这是一个非常简单的解决方案,如下所示:
队列服务只是监听事件(在本例中来自 AWS SQS),一旦有事件通过,它就会被触发到命令控制器进行处理。
@Service
@EnableSqs
public class QueueListener {
private final static String SERVICE = "http://instance-service/instances";
@Autowired
private JsonTransformService jsonTransformService;
@Autowired
private RestTemplate restTemplate;
@MessageMapping("${queues.instanceEvents}")
public void instanceCommandHandler(String payload) {
// Transform the payload to the object so we can get the preset JWT
Instance instance = jsonTransformService.read(Instance.class, payload);
// Load the JWT into the internal request header, without this a 403 is thrown
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + instance.getUserToken());
HttpEntity<String> instanceEntity = new HttpEntity<>(payload, headers);
// Decide and set where to fire the request to
String endpoint;
switch (instance.getSwordfishCommand()) {
case "start": {
endpoint = "/start";
break;
}
case "stop": {
endpoint = "/stop";
break;
}
case "create": {
endpoint = "/create";
break;
}
case "reboot": {
endpoint = "/reboot";
break;
}
case "terminate": {
endpoint = "/terminate";
break;
}
default: {
endpoint = "/error";
}
}
// Fire the initial string payload through to the correct controller endpoint
restTemplate.exchange(SERVICE + endpoint, HttpMethod.POST, instanceEntity, String.class);
}
}
还有一个非常简单的 REST 控制器,用于执行任务
@RestController
@RequestMapping("/instances")
public class InstanceCommandController {
@Autowired
private EC2Create ec2Create;
@Autowired
private EC2Start ec2Start;
@Autowired
private EC2Stop ec2Stop;
@Autowired
private EC2Reboot ec2Reboot;
@Autowired
private EC2Terminate ec2Terminate;
@Autowired
private JsonTransformService jsonTransformService;
@PostMapping("/create")
public void create(@RequestBody String payload) {
ec2Create.process(jsonTransformService.read(Instance.class, payload));
}
@PostMapping("/start")
public void start(@RequestBody String payload) {
ec2Start.process(jsonTransformService.read(Instance.class, payload));
}
@PostMapping("/stop")
public void stop(@RequestBody String payload) {
ec2Stop.process(jsonTransformService.read(Instance.class, payload));
}
@PostMapping("/reboot")
public void reboot(@RequestBody String payload) {
ec2Reboot.process(jsonTransformService.read(Instance.class, payload));
}
@PostMapping("/terminate")
public void terminate(@RequestBody String payload) {
ec2Terminate.process(jsonTransformService.read(Instance.class, payload));
}
}
这很好地遵循了 CQRS 模式,同时仍然在每次调用时对用户进行身份验证。对我来说这非常有用,因为我有一个 AmazonEC2Async 客户端,它在每个请求中使用用户自己的访问权限和秘密令牌。
为帮助干杯!