springcloud微服务学习笔记14:服务发现Discovery
Discovery功能:
对于注册进eureka里面的微服务,可以通过服务发现来获得服务的信息
1.修改cloud-provider-payment8001的controller
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Resource
private DiscoveryClient discoveryClient;
@Value("${server.port}")
private String serverPort;
@PostMapping("/payment/creat")
public CommonResult<Payment> create(@RequestBody Payment payment){
int result=paymentService.create(payment);
log.info("******插入结果"+result);
if (result>0){
return new CommonResult(200,"success",result);
}else {
return new CommonResult(400,"fail",null);
}
}
@GetMapping("/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
Payment payment=paymentService.getPaymentById(id);
log.info("******查询结果"+payment);
if(payment!=null) {
return new CommonResult(200, "success,serverPort:"+serverPort, payment);
}else {
return new CommonResult(400,"fail",null);
}
}
@GetMapping("/payment/discovery")
public Object discovery(){
List<String> services=discoveryClient.getServices();
for (String service:services){
log.info("***********service:"+service);
}
List<ServiceInstance> serviceInstances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
for (ServiceInstance serviceInstance:serviceInstances){
log.info(serviceInstance.getHost()+"\t"+serviceInstance.getInstanceId()+"\t"+serviceInstance.getPort()+"\t"+serviceInstance.getUri());
}
return this.discoveryClient;
}
}
2.8001的主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class,args);
}
}
3.测试
3.1启动eurekaServer
3.2启动8001
地址:http://localhost:8001/payment/discovery



浙公网安备 33010602011771号