springCloud中集成了consul实现注册中心的功能。consul是go语言写的。
1.环境搭建
2.建provider,并实现注册
3.建consumer,并实现注册
1.环境搭建
官网:Https://www.consul.io/intro/index.html
下载: https://www.consul.io/downloads.htm
查看安装情况 只要consul --version 出版本号即可。
1.2 启动 consul agent -dev
1.3 访问 http://localhost:8500 应该就可以访问注册中心了。如下图所示。
2.建provider,并实现注册
2.1POM.XML 多了一个consul服务发现的依赖
<!--SpringCloud consul-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
2.2application.yml
###consul服务端口号
server:
port: 8006
spring:
application:
name: consul-provider-payment
####consul注册中心地址
cloud:
consul:
host: localhost
port: 8500
discovery:
#hostname: 127.0.0.1
service-name: ${spring.application.name}
2.3 主启动类 无区别
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8006 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8006.class, args);
}
}
2.4业务类 controller 无区别
@RestController
@Slf4j
public class PaymentController
{
@Value("${server.port}")
private String serverPort;
@RequestMapping(value = "/payment/consul")
public String paymentConsul()
{
return "springcloud with consul: "+serverPort+"\t "+ UUID.randomUUID().toString();
}
}
2.5 验证
输入:http://localhost:8006/payment/consul
3.建consumer,并实现注册
application.yml
###consul服务端口号
server:
port: 80
spring:
application:
name: cloud-consumer-order
####consul注册中心地址
cloud:
consul:
host: localhost
port: 8500
discovery:
#hostname: 127.0.0.1
service-name: ${spring.application.name}
主启动 无区别 配置BEAN
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
controller
public class OrderConsulController
{
public static final String INVOKE_URL = "http://consul-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/consul")
public String paymentInfo()
{
String result = restTemplate.getForObject(INVOKE_URL+"/payment/consul",String.class);
return result;
}
}
4. 验证
启动一个 provider 自测通过
启动两个:consumer调用
看注册中心是否注册上