构建第一个SpringCloud项目Eureka、Eureka-client

第一步,创建一个Maven工程

第二步,在Maven工程创建springcloud-eureka-server

添加pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
    dependency>

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
dependencies>
添加application.yml
server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
在项目启动加上@EnableEurekaServer注解
@EnableEurekaServer
@SpringBootApplication
public class SpringcloudEurekaServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudEurekaServerApplication.class, args);
    }

}
启动SpringcloudEurekaServerApplication

在浏览器地址栏输入http:localhost:8761,显示如下结果
构建第一个SpringCloud项目Eureka、Eureka-client_第1张图片

第三步,在Maven工程创建springcloud-eureka-client

添加pom.xml
<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
    dependency>

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>5.1.5.RELEASEversion>
        <scope>compilescope>
    dependency>
dependencies>
添加application.yml
eureka:
  client:
    service-url:
      #向三个服务端分别注册
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8762
spring:
  application:
    name: service-hi
在项目启动加上@EnableDiscoveryClient注解
@EnableDiscoveryClient
@SpringBootApplication
public class SpringcloudEurekaClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudEurekaClientApplication.class, args);
    }

}
添加Controller
@Controller
public class DcController {

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/dc")
    public String dc() {
        String services = "Services: " + discoveryClient.getServices();
        System.out.println(services);
        return services;
    }
}
启动SpringcloudEurekaClientApplication

访问http://localhost:8762/dc,在控制台会显示
构建第一个SpringCloud项目Eureka、Eureka-client_第2张图片
在http://localhost:8761,Instances currently registered with Eureka中会发现一个Eureka客户端
构建第一个SpringCloud项目Eureka、Eureka-client_第3张图片

你可能感兴趣的:(SpringCloud)