服务中心的搭建
添加依赖
<!--eureka-server服务端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
配置 application.yaml
server:
port: 7003
eureka:
instance:
#eureka 服务端的实例名称
hostname: eurekaserver7003
client:
#false代表不向注册中心注册自己
register-with-eureka: false
#表示自己就是一个注册中心,职责就是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
#设置与EurekaServer 交互的地址查询服务和注册中心的地址----单机版
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
在启动类上添加注解
@EnableEurekaServer
@SpringBootApplication
public class EurekaServer_7002 {
public static void main(String[] args) {
SpringApplication.run(EurekaServer_7002.class);
}
}
服务注册
添加依赖
<!-- 将微服务provider侧注册进eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
添加注册地址
#将客户端注册进Eureka_7001服务列表中
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka/
在启动类上添加注解
@SpringBootApplication
@EnableEurekaClient
public class Provider_Dept_8001 {
public static void main(String[] args) {
SpringApplication.run(Provider_Dept_8001.class);
}
}
给客户端也就是服务端设置别名和显示ip信息
eureka:
instance:
instance-id: providerdept8001
prefer-ip-address: true #访问路径可以显示IP地址
info 信息的构建
<build>
<finalName>SpringCloudParent</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimit>$</delimit>
</delimiters>
</configuration>
</plugin>
</plugins>
</build>
info:
app.name: microservicecloud
company.name: microservicecloud
build.artifactId: $project.artifactId$
build.version: $project.version$
服务发现
在Controller中注入
/**
* 服务发现
*/
@Autowired
@Qualifier("discoveryClient")
private DiscoveryClient client;
@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
public Object discovery()
{
List<String> list = client.getServices();
System.out.println("**********" + list);
List<ServiceInstance> srvList = client.getInstances("PROVIDERDEPT_8001");
for (ServiceInstance element : srvList) {
System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
+ element.getUri());
}
return this.client;
}
|
|