1.官網
https://learn.hashicorp.com/consul/getting-started/install.html
2.訂單服務
? 2.1 POM
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
? 2.2 YML
server:port: 80spring:application:name: cloud-ordercloud:consul:host: localhostport: 8500discovery:service-name: ${spring.application.name}
? 2.3 配置類
@Configuration
public class ApplicationContextConfig {@LoadBalanced@Beanpublic RestTemplate getRestTemplate(){return new RestTemplate();}}
? 2.4 控制器
@RestController()
@RequestMapping("order")
@Slf4j
public class OrderController {@Autowiredprivate RestTemplate restTemplate;public static final String PAYMENT_URL = "http://cloud-payment";@GetMapping("/get/{id}")public CommonResult<Payment> 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
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
? 3.2 YML
server:port: 8006spring:application:name: cloud-paymentcloud:consul:host: localhostport: 8500discovery:service-name: ${spring.application.name}
? 4.5 主程序?
@RestController()
@RequestMapping("/payment")
public class PaymentController {@Value("${server.port}")private int port;@GetMapping("get/{id}")public CommonResult<Payment> 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