说明:本次主要完成将Spring Boot应用加入Eureka的服务治理体系(换句话说就是将一个微服务应用向服务注册中心发布自己)
1.修改pom.xml文件(增加Spring Cloud Eureka模块的依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ml</groupId>
<artifactId>hello-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hello-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.新建HelloController类,创建/hello接口,通过注入DiscoveryClient对象,在日志中打印出服务的相关内容
@RestController
public class HelloController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private DiscoveryClient client;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() {
List<String> service = client.getServices();
//System.out.println("services:" + service.get(0));
logger.info("services:" + service);
return "hello world";
}
}
3.在主类中通过加入@EnableDiscoveryClient注解,激活Eureka中的DiscoveryClient实现(自动化配置,创建DiscoveryClient接口针对Eureka客户端的EnableDiscoveryClient实例),才能实现上述Controller中对服务信息的输出。
@SpringBootApplication
@EnableDiscoveryClient
public class HelloServerApplication {
public static void main(String[] args) {
SpringApplication.run(HelloServerApplication.class, args);
}
}
4.最后需要在application.properties配置文件中添加以下内容
#配置服务器端口
server.port=1112
#服务命名
spring.application.name=hello-server
#指定服务注册中心地址
eureka.client.serviceurl.defaultZone=http://localhost:1111/eureka/
#ribbon.eureka.enabled=true