Spring Cloud (II): service governance --Spring Cloud Eureka

  Service management is a micro-service architecture and the most basic core modules, the main role is to achieve automation of service instances each micro registration and discovery. Spring Cloud Eureka is part of the Spring Cloud Netflix Micro suite of services, based Netflix EureKa made two packages, service management function mainly responsible for the micro-service architecture.

  Eureka's service found to contain two major components, the server discovery component (Eureka Server) and client discovery component (Eureka Client). Server discovery component is also known as the service registry, which offers a service registration function, the client discovery component mainly used for registration and discovery processing services. According to a character class, in Eureka, the service discovery mechanism contains three roles: service registry, service providers and service consumers.

First, the use Eureka registration services

  1. Create a maven parent project

  Create a parent maven project, named   springcloud-Eureka-parent  , and add Spring Cloud version dependency information in the project pom.xml in:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.fix</groupId>
    <artifactId>springcloud-eureka-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--父依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <!--编码以及Java版本-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <!--Spring Boot包含的Maven插件,可以将项目打包成可以执行的Jar文件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

  2. build a service registry

  In the parent project  springcloud-eureka-parent  , create sub-module Maven  springcloud-eureka-server  as a service registry (server engineering), adding a dependency in pom.xml:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud-eureka-parent</artifactId>
        <groupId>com.fix</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-eureka-server</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
</project>

  Create a profile application.yml, increased port number in the configuration file configuration information, as follows:

server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone:
        http://${eureka.instance.hostname}:${server.port}/eureka/

  The above configuration represents the port number eureka registry for 8761, should be an example for all services registered to this port. eureka.instance.hostname  shows an example of the name of the eureka registry is localhost,  the Register-with-eureka: false  indicates that the Spring Boot application for the registration center, registration center does not need to register themselves. Registry-FETCH: false  configuration because responsibility is to maintain a registry service instance, you do not need to search services. The  defaultZone  is an address registry.

  Next, create a project started class, and add  @EnableEurekaServer  annotation is used to declare the class label is a Erueka Server:

package com.fix.springcloud.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerMain {
    public static void main(String [] args){
        SpringApplication.run(EurekaServerMain.class,args);
    }
}

  Start  springcloud-eureka-server  module in the browser to access: HTTP: // localhost: 8761 /  can see the information panel Eureka:

At this point already registered to display the current service instance Eureka is empty "Instances currently registered with Eureka" in.

  3. To build the client project

  In the parent project   springcloud-eureka-parent   , create sub-module Maven   springcloud-eureka-user   as a client project, adding a dependency in pom.xml:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud-eureka-parent</artifactId>
<groupId>com.fix</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>springcloud-eureka-user</artifactId>
<dependencies>
     <!--Finchley, Greenwich version of spring cloud, create a client project when the need to rely on the introduction of the -> 
<groupId> org.springframework.boot </ groupId>
<dependency>

<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>

</project>

  Application.yml create profiles, configure Eureka service instances in the configuration file the port number, server address, etc., as follows:

Server: 
Port: 8000
eureka:
instance:
the prefer-ip-address: # to true whether the host Ip
Client:
Service-url:
defaultzone: HTTP: // localhost: 8761 / eureka / # to specify the server address eureka
the Spring:
the Application:
name: springcloud-eureka-user

  Create a client bootstrap class  EurekaUserMain  , and add  @EnableEurekaClient  annotation is used to declare a class label Eureka client components. Details are as follows:

@SpringBootApplication
@EnableEurekaClient
public class EurekaUserMain {
    public static void main(String[] args) {
        SpringApplication.run(EurekaUserMain.class, args);
    }
}

  Start  springcloud-eureka-server  after module start  springcloud-eureka-user  module, revisit HTTP: // localhost: 8761 /  , you can see there has been just created in the "Instances currently registered with Eureka" in  SPRINGCLOUD-EUREKA-USER  example:

  同时,可以看到该页面有红色的字体提示“EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.”,这是因为本地调试时触发了Eureka Server的自我保护机制,该机制会使注册中心维护的实例不是很准确。在本地开发时候,可以在服务注册中心中配置 eureka.server.enable-self-preservation=false 参数来关闭保护机制。

二、使用Eureka实现服务间的调用

  在上一步中,已经将用户服务 springcloud-eureka-user 注册到了服务注册中心,接下来将创建一个订单服务,并实现用户服务和订单服务之间的调用。

  1. 搭建订单服务工程

  在父工程 springcloud-eureka-parent 中,创建子模块 springcloud-eureka-order ,pom.xml文件和 springcloud-eureka-user 的类似,具体内容如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud-eureka-parent</artifactId>
        <groupId>com.fix</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-eureka-order</artifactId>
    <dependencies>
        <!--Finchley,Greenwich版本的spring cloud,创建客户端工程的时候需要引入该依赖-->
        <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>
    </dependencies>
</project>

  创建配置文件 application.yml ,配置Eureka服务实例的端口号,服务注册中心地址等信息,具体内容如下:

server:
  port: 7900
eureka:
  instance:
    prefer-ip-address: true     #是否显示主机的Ip
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/     #指定eureka服务端地址
spring:
  application:
    name: springcloud-eureka-order    #指定应用名称

  创建客户端引导类 EurekaOrderMain :

@SpringBootApplication
@EnableEurekaClient
public class EurekaOrderMain {
    public static void main(String[] args) {
        SpringApplication.run(EurekaOrderMain.class, args);
    }
}

  创建订单实体类:

package com.fix.springcloud.eureka.pojo;

public class Order {
    private String id;
    private Double price;
    private String receiverName;
    private String receiverAddress;
    private String receiverPhone;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getReceiverName() {
        return receiverName;
    }

    public void setReceiverName(String receiverName) {
        this.receiverName = receiverName;
    }

    public String getReceiverAddress() {
        return receiverAddress;
    }

    public void setReceiverAddress(String receiverAddress) {
        this.receiverAddress = receiverAddress;
    }

    public String getReceiverPhone() {
        return receiverPhone;
    }

    public void setReceiverPhone(String receiverPhone) {
        this.receiverPhone = receiverPhone;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id='" + id + '\'' +
                ", price=" + price +
                ", receiverName='" + receiverName + '\'' +
                ", receiverAddress='" + receiverAddress + '\'' +
                ", receiverPhone='" + receiverPhone + '\'' +
                '}';
    }
}

  创建订单Controller,内容如下:

package com.fix.springcloud.eureka.controller;

import com.fix.springcloud.eureka.pojo.Order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {
    /**
     * 通过订单id查询订单信息
     * @param id 订单id
     * @return 订单详情
     */
    @GetMapping("/order/{id}")
    public String findOrderById(@PathVariable String id){
        Order order =new Order();
        order.setId("123");
        order.setPrice(200.50);
        order.setReceiverName("张三");
        order.setReceiverAddress("陕西西安");
        order.setReceiverPhone("123456799");
        return order.toString();
    }
}

  2. 编写用户服务功能

  在 springcloud-eureka-user 实例工程的引导类中,创建 RestTemplate 的Spring实例,代码如下:

@SpringBootApplication
@EnableEurekaClient
public class EurekaUserMain {
    public static void main(String[] args) {
        SpringApplication.run(EurekaUserMain.class, args);
    }

    @Bean
    public RestTemplate initRestTemplate(){
        return new RestTemplate();
    }
}

  创建用户Controller,调用订单Controller接口,查询订单信息,具体代码如下:

package com.fix.springcloud.eureka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/findOrderByUser/{id}")
    public String findOrderByUser(@PathVariable String id) {
        int orderId = 123;
        return this.restTemplate.getForObject("http://localhost:7900/order/" + orderId, String.class);
    }
}

  3.启动各Eureka实例进行测试

   依次启动服务注册中心, springcloud-eureka-order 以及 springcloud-eureka-user 实例,访问注册中心管理界面 http://localhost:8761/ 确认两个服务实例已经注册成功:

  访问 springcloud-eureka-user 实例的接口接口 http://localhost:8000/findOrderByUser/123,可以看到有数据正常返回:

  表示使用Eureka进行服务间接口调用成功。

Guess you like

Origin www.cnblogs.com/fengweiweicoder/p/11032930.html