單獨使用Eureka實現服務發現、服務註冊

目錄

Eureka服務端

1.啓動類 

2.yml 

3.pom 

Eureka客戶端

1.啓動類

2. yml

3. pom

4. 服務發現工具類

4.1 修改服務發現工具類-用於正式環境


Eureka服務端

1.啓動類 

package com.eureka;

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

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

2.yml 

server:
  port: 8761  
eureka:
  instance:
    hostname: 192.168.2.190
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  server:
    # 測試時關閉自我保護機制,保證不可用服務及時踢出
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 3000
  

3.pom 

<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.test</groupId>
  <artifactId>eureka</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
   <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.3.4.RELEASE</version>
        </dependency>
	</dependencies>
	<!--引入spring cloud依賴-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!--添加spring-boot 依賴-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>

Eureka客戶端

1.啓動類

package com.cq;

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

@EnableEurekaClient
@SpringBootApplication
public class AppOrder {

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

}

2. yml

server:
  port: 8002
  
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
    register-with-eureka: true
    fetch-registry: true
  instance:
    #Eureka服務端在收到最後一次心跳之後等待的時間上限,單位爲秒,超過則刪除(客戶端告訴服務端按照此規則等待自己)
    lease-expiration-duration-in-seconds: 3
    ##Eureka客戶端向服務端發送心跳的時間間隔,單位爲秒(客戶端告訴服務端自己會按照該規則)
    lease-renewal-interval-in-seconds: 1
  
spring:
  application:
    name: service-client

3. pom

<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.cq</groupId>
  <artifactId>client</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath /> 
	</parent>
	
	<dependencies>
		 <!--eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.3.4.RELEASE</version>
        </dependency>
	</dependencies>

 <!--引入spring cloud依賴-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</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>

4. 服務發現工具類

package com.cq.controller;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 取模獲取服務註冊的URL
 * 
 * @author qizhentao
 * @version V1.0
 */
@RestController
public class PollURL {
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	//初始化請求數
        public static AtomicInteger requestCnt = new AtomicInteger(1);

    /**
     * 從服務列表中選擇一個地址
     * @return ip:端口
     */
	@RequestMapping("/getUrl")
	public String getUrl(){
		long currentTimeMillis = System.currentTimeMillis();// 耗時統計
		//在註冊中心獲取對應的服務列表
        List<ServiceInstance> list = discoveryClient.getInstances("service-client");
        if(list == null) {
            return null;
        }
 
        //獲取服務列表的數量
        int serviceSize = list.size();
        //請求數 % 服務列表數量 得到下標
        int index = requestCnt.get() % serviceSize;
        //將請求數增加1
        requestCnt.incrementAndGet();
        //根據計算的下標選取一個服務地址
        System.out.println("選址用時:"+(System.currentTimeMillis() - currentTimeMillis));
        return list.get(index).getUri().toString();
	}
	
}

4.1 修改服務發現工具類-用於正式環境

package com.chuangqi.core.rpc;

import com.chuangqi.core.Conf;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * RPC服務發現,從Eureka獲取服務地址
 *
 * @author qizhentao
 * @version V1.0
 */
@Log4j2
public class ServerDiscover {

    // RPC遠程調用案例說明!
    /**
        // Eureka客戶端
        @Resource
        private DiscoveryClient discoveryClient;

         //調用sim-node-server服務的銷燬資源方法
        @GetMapping("/getUrl")
        public String getUrl() {
            // 1. 封裝參數
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("_method", "delete"); // 表示是Restful形式的delete請求
            // 2. 獲取服務ip:port
            String address = ServerDiscover.getSimNodeServerAddress(discoveryClient);
            // 3. RPC遠程調用具體接口
            String post = HttpUtil.post(address + "/master-node/resource", paramMap);
            return post;
        }
     */

    /** 初始化請求數Eureka */
    public static AtomicInteger requestCnt = new AtomicInteger(1);

    /**
     * 獲取‘1服務’集羣中的一個地址
     *
     * @return ip:port
     */
    public static String getSimDisplayServerAddress(DiscoveryClient client) {
        return new ServerDiscover().getChooseAddress("1服務名稱", client);
    }

    /**
     * 獲取‘2服務’集羣中的一個地址
     *
     * @return ip:port
     */
    public static String getSimNodeServerAddress(DiscoveryClient client) {
        return new ServerDiscover().getChooseAddress("2服務名稱", client);
    }

    /**
     * 根據服務名稱從服務列表中獲取一個地址
     *
     * @param serverName 服務名
     * @param client     Eureka客戶端接口DiscoveryClient
     * @return ip:port
     */
    public static String getAddress(String serverName, DiscoveryClient client) {
        return new ServerDiscover().getChooseAddress(serverName, client);
    }

    private String getChooseAddress(String serverName, DiscoveryClient client) {
        long start = System.currentTimeMillis();// 耗時統計

        //在註冊中心獲取對應的服務列表
        List<ServiceInstance> list = client.getInstances(serverName);
        if (list == null || list.size() == 0) {
            log.info("{}未發現服務", serverName);
            return "";
        }

        //獲取服務列表的數量
        int serviceSize = list.size();
        //請求數 % 服務列表數量 得到下標
        int index = requestCnt.get() % serviceSize;
        //將請求數增加1
        requestCnt.incrementAndGet();
        //根據計算的下標選取一個服務地址
        String address = list.get(index).getUri().toString();
        long end = System.currentTimeMillis();
        log.info("{}服務選址{}耗時:{}", serverName, address, end - start);
        return address;
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章