SpringCloud集成Eureka客户端
在集成客户端之前应首先集成服务端
一:创建Eureka客户端maven项目,添加客户端依赖:
<dependencies>
<!--引入Eureka的客户端依赖,不包含springboot-start-web,所以要单独引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入springboot-start-web依赖,必须引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--此依赖为自定义的公共模块打成jar包引入-->
<dependency>
<groupId>org.example</groupId>
<artifactId>SpringCloud_Pojo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
二:编写application.yml
spring:
application:
name:UserServer #服务的应用名称
server:
port:10002 #user服务端口号
eureka:
client:
serviceUrl: #Eureka客户端配置,指向注册中心地址
defaultZone:http://localhost:10001/eureka/
registry-fetch-interval-seconds:10 #修改从客户端拉取信息的时间10s
instance:
prefer-ip-address:true #使用ip+端口号进行注册
instance-id:UserServer-10002 #实例id,一般为服务名+端口号
三:编写启动类
package cn.ybl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class UserServer {
public static void main(String[] args) {
SpringApplication.run(UserServer.class);
}
}
需先启动Eureka服务端再启动客户端才可以将这个服务注册进注册中心
四:客户使用RestTemplate的方法
在启动类/配置类中注册bean
/**
* 注册RestTemplate工具类
* @return
*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
然后在需要的地方使用@Autowire注入即可发起调用其他服务的接口