1、在pom.xml中添加相关依赖,也可以在新建项目时,选择要添加的依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</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>
2、新建HelloController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
@RestController
public class HelloController {
private final Logger logger = Logger.getLogger(String.valueOf(getClass()));
@Qualifier("eurekaRegistration")
@Autowired
private Registration registration;
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value="/hello",method = RequestMethod.GET)
public String index(){
logger.info("/hello,host:"+ registration.getHost()+",service_id:"+registration.getServiceId());
return "hello world";
}
}
3、在启动类上添加注册@EnableDiscoveryClient
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}
}
4、在applicatioin.properties中添加配置。
#配置服务名
spring.application.name = hello-service
#配置服务注册中心的地址
eureka.client.serviceUrl.defaultZone= http://localhost:1111/eureka/
5、启动服务注册中心,然后启动服务提供者,即本测试。
在服务提供者的控制台可以看到服务注册成功的日志。如下图标红的日志。
在服务注册中心的控制台,也可以看到服务提供者注册成功的日志信息,如下图标红位置所示。
6、通过eureka的信息面板,在Instances currently registered with Eureka一栏中看到服务的注册信息。访问 http://localhost:8080/hello。