使用Consul
随着eureak2.x不再开源,意味着我们需要转向使用其他的服务注册中心,今天来学习下Consul
下载
启动服务
consul.exe agent -dev -node machine
通过url:http://localhost:8500 可以看到ui界面
## 服务提供者
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
注意:如果这里没有添加actuator依赖,则会导致服务无法被发现
创建启动类
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ServiceProviderApplication {
@RequestMapping("/")
public String home() {
return "Hello world";
}
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class,args);
}
}
配置yml
spring:
cloud:
consul:
host: localhost
port: 8500
application:
name: provider
management:
server:
port: 4453
服务消费者
spring-cloud-consul也是能集成feign,所有这里我们使用feign做restful调用客户端
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
启动类
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableFeignClients(basePackages = "com.example")
public class ServiceComsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceComsumerApplication.class,args);
}
@Autowired
private RemoteClient remoteClient;
@GetMapping("/feign")
public String index(){
return remoteClient.home();
}
}
feign接口
@FeignClient(name = "provider")
public interface RemoteClient {
@RequestMapping("/")
String home();
}
yml配置
spring:
cloud:
consul:
host: localhost
port: 8500
application:
name: comsumer
management:
server:
port: 4452
server:
port: 8002
启动俩个非服务,访问http://localhost:8002/feign