MessagesComtroller.java
1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.zhongweixian.comtroller;
import com.zhongweixian.entity.MessagesReqBody;
import com.zhongweixian.service.MessagesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author : caoliang
*
* @date : 2017/10/26:下午1:52
*/
@RestController
public class MessagesComtroller {
Logger logger = LoggerFactory.getLogger(MessagesComtroller.class);
@Autowired
private MessagesService messagesService;
// 服务注册
@Autowired
private Registration registration;
// 服务发现客户端
@Autowired
private DiscoveryClient discoveryClient;
@PostMapping("/sendMessage")
public String sendMessage(@RequestBody MessagesReqBody messagesReqBody) {
ServiceInstance instance = serviceInstance();
logger.info("provider service, host :{} , service_id:{} " , instance.getHost()
+ ", service_id = " , instance.getServiceId());
messagesService.sendMessage(messagesReqBody);
return "Hello,Provider!";
}
/**
* 获取当前服务的服务实例
*
* @return ServiceInstance
*/
public ServiceInstance serviceInstance() {
List<ServiceInstance> list = discoveryClient.getInstances(registration.getServiceId());
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
}