3.cloud-Consul服务注册与发现

1.官网

https://learn.hashicorp.com/consul/getting-started/install.html

2.订单服务

  2.1 POM


            org.springframework.cloud
            spring-cloud-starter-consul-discovery

  2.2 YML

server:
  port: 80

spring:
  application:
    name: cloud-order
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

  2.3 配置类

@Configuration
public class ApplicationContextConfig {

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

  2.4 控制器

@RestController()
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    public static final String PAYMENT_URL = "http://cloud-payment";


    @GetMapping("/get/{id}")
    public CommonResult getPayment(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

}

  2.5 主程序 

@EnableDiscoveryClient
@SpringBootApplication
public class OrderConsulMain {
    public static void main(String[] args) {
        SpringApplication.run(OrderConsulMain.class, args);
    }
}

3.支付服务

  3.1 POM

 
            org.springframework.cloud
            spring-cloud-starter-consul-discovery

  3.2 YML

server:
  port: 8006

spring:
  application:
    name: cloud-payment
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

  4.5 主程序 

@RestController()
@RequestMapping("/payment")
public class PaymentController {

    @Value("${server.port}")
    private int port;

    @GetMapping("get/{id}")
    public CommonResult get(@PathVariable("id") long id)
    {
        Payment payment = new Payment();
        payment.setId(id);

        return new CommonResult(200, this.port +"查询成功",payment);
    }

}

4.consul启动脚本

cd /d %~dp0
consul agent -dev
pause

你可能感兴趣的:(SpringCloud,consul)