英文:
Make request just after the initialization using Spring Boot
问题
我有两个HTTP服务。第一个是在线的,它可以接收SEND_DATA
请求,然后使用POST请求SAVE_DATA
将数据发送给第二个服务。我想使第二个服务在启动时能够向第一个服务发出SEND_DATA
请求,然后通过SAVE_DATA
请求获取数据。问题是,如果我在第二个服务中使用@Autowired
发送请求,第一个服务会接收此请求并将其发送给第二个服务,但是第二个服务在那时还没有完全初始化,因此无法接收此请求。什么是解决此问题的最佳方法?
第一个服务:
@GetMapping(value = SEND_DATA)
public ResponseEntity<String> sendData() {
...
postRequest(SAVE_DATA)
...
}
第二个服务:
@Autowired
public Second() {
...
getRequest(SEND_DATA)
...
}
@PostMapping(value = SAVE_DATA, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> saveData(@RequestBody String value) {
save(value)
}
英文:
I have two http services. First one is online and it can get request SEND_DATA and than it sends data to second one using post request SAVE_DATA. I want to make second service when it starts to be able to make request SEND_DATA to first one and than get it by request SAVE_DATA. The problem is, if I send request from second one in autowired, first gets this request and sends it to second, but the second isn't fully initialized by that time and it can't get this request. What is the best solution to this?
first
@GetMapping(value = SEND_DATA)
public ResponseEntity<String> sendData() {
...
postRequest(SAVE_DATA)
...
}
second
@Autowired
public Second() {
...
getRequest(SEND_DATA)
...
}
@PostMapping(value = SAVE_DATA, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> saveData(@RequestBody String value) {
save(value)
}
答案1
得分: 1
如果您有一个分布式系统,您不能依赖于2个Bean(服务)之间的内部通信。我建议您在调用之前编写代码进行可用性检查。
@Service
public class FirstService {
private AtomicBoolean isSecondServiceOk;
@Scheduled(fixedDelay = 1_000L)
void checkingSecondServiceAvailability(){
... 检查来自SecondService的响应,如果有响应,
isSecondServiceOk.set(true)
}
... 在调用SecondService之前检查isSecondServiceOk是否可用
}
英文:
If you have a distributed system, you cannot rely on internal communication between 2 beans(services). I suggest you having code to check availability before calling.
@Service
public class FirstService {
private AtomicBoolean isSecondServiceOk;
@Scheduled(fixedDelay = 1_000L)
void checkingSecondServiceAvailability(){
... check response from SecondService if it respond,
isSecondServiceOk.set(true)
}
... check isSecondServiceOk available before calling SecondService
}
答案2
得分: 0
使用 @PostConstruct
:
@Service
public class MyService {
@Autowired
private OtherService otherService;
@PostConstruct
private void postConstruct() {
otherService.doSomething();
}
}
这个方法必须是 void
类型,但可以有任何可见性(public、protected、private等),在此 bean 初始化完成后调用,当然这也意味着被注入的 bean 也已经初始化完成。
英文:
Use @PostConstruct
:
@Service
public class MyService {
@Autowired
private OtherService otherService;
@PostConstruct
private void postConstruct() {
otherService.doSomething();
}
The method, which must be void but can have any visibility, is called after this bean is initialized, and that means of course that the injected bean is initialized too.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论