二、Spring Cloud 的 Eureka 組件

Spring 微服務架構



Spring cloud 微服務解決方案(組件集), Spring cloud 他不是一蹴而就的,在不同階段,引用對應組件:

        1) 服務變多了,引入註冊中心?                                    Spring Cloud - Eureka
        2) 服務間調用的負載均衡?                                           Spring Cloud - Ribbon 客戶端負載均衡
        3) 配置如何管理?如何動態更新?                                Spring Cloud - Config
        4) 服務限流?                                                                  Spring Cloud - Hystrix  熔斷中心
        5) AService -> BService -> CService 調用鏈路追蹤?  Spring Cloud - Sleuth
        6) 網關代理(鑑權)?                                                     Spring Cloud - Zuul
        7) 消息總線?                                                                  Spring Cloud - BUS

Zookeeper 與 Eureka 差別
        1) Zookeeper 不是專業處理Eureka的工具
        2) 和程序的需要定製開發
        3) 選舉Leader,不能服務




一、Eureka Server

     查看 Eureka Server 的Web管理界面   http://localhost:8761
     查看 Eureka Server 的服務實例           http://localhost:8761/eureka/apps

      1) Maven配置

<?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.itmuch.cloud</groupId>
	<artifactId>microservice-eureka-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>eureka-server</name>
	<description>Simple for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.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>
		<spring-cloud.version>Dalston.SR3</spring-cloud.version>
	</properties>

	<dependencies>
		<!-- Eureka 服務  -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka-server</artifactId>
		</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)  yml 文件配置

server:
  port: 8761

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false   #表示是否將自己註冊到Eureka Server中,默認爲true, 由於當前應用就是 Eureka Server, 故而設置爲false
    fetch-registry: false         #表示是否從 Eureka Server中獲取註冊信息, 默認爲true, 因爲這是一個單點的 Eureka Server, 不需要同步其它的 Eureka Server 節點的數據, 故而設置爲 false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/  # 設置與Eureka Server交互的地址, 查詢服務和註冊服務都需要依賴這個地址. 默認http://localhost:8761/eureka; 多個地址可以使用","分隔
      

        3) 主程序代碼

package com.itmuch.cloud;

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

@SpringBootApplication
@EnableEurekaServer    // 開啓這是一個 Eureka Server 程序
public class EurekaServerApplication {

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

二、生產者程序

        1) Maven 配置

<?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.itmuch.cloud</groupId>
	<artifactId>microservice-cloud-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>cloud-service</name>
	<description>Simple for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.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>
		<spring-cloud.version>Dalston.SR3</spring-cloud.version>
	</properties>

	<dependencies>
		<!-- Spring Eureka 客戶端 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		
		<!-- Spring Cloud -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter</artifactId>
		</dependency>
		
		<!-- Spring Boot Actuator 監控端口 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		
		<!-- JPA依賴包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		
		<!-- Web項目依賴包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- MySQL -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</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)  yml 文件配置

server:
  port: 8080
  session:
    timeout: 30
  tomcat:
    max-threads: 0
    uri-encoding: UTF-8
    
spring:
  application:
    #表示註冊到Eureka上的應用名稱
    name: cloud-service
  datasource:
    url: jdbc:mysql://localhost:3306/boot
    username: root
    password: xshdb
    driver-class-name: com.mysql.jdbc.Driver
    
  jpa:
    # Specify the DBMS
    database: MYSQL
    # Show or not log for each sql query
    show-sql: true
    # Hibernate dll auto (create, create-drop, update)
    hibernate:
       ddl-auto: update

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true     # 表示將自己的IP註冊到Eureka Serverk, 如果不配置該屬性或將它改爲false,則表示註冊微服務所在操作系統的hostname到Eureka Server
    

        3)  主程序

package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class CloudServiceApplication {

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


        4) User Entity 類

package com.itmuch.cloud;

import java.io.Serializable;
import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	
	@Column
	private String username;
	
	@Column
	private String name;
	
	@Column
	private Integer age;
	
	@Column
	private BigDecimal balance;

	public Long getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public BigDecimal getBalance() {
		return balance;
	}

	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}
	
}

        5)  Controller 控制檯

package com.itmuch.cloud;

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;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/get/{id}")   // 在Spring 4.3規則中,@GetMapping等價於@RequestMapping(method = RequestMethod.GET), 用於簡化, 同理還有@PostMapping, @PutMapping, @DeleteMapping, @PatchMapping等
	public User findById(@PathVariable Long id) {
		User findOne = this.userRepository.findOne(id);
		System.out.println(findOne.toString());
		return findOne;
	}
	
}

        6)  DAO 層

package com.itmuch.cloud;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}


三、 消費者

測試地址: http://localhost:8100/eureka/1                      好像有問題, 根據服務名找不到實例
                 http://localhost:8100/discovery/1


        1)  Maven 配置
<?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.itmuch.cloud</groupId>
	<artifactId>microservice-cloud-consumer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>cloud-consumer</name>
	<description>Simple for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.6.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>
		<spring-cloud.version>Dalston.SR3</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>		
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</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) yml 文件配置
server:
  port: 8100
  
spring:
  application:
    name: cloud-consumer

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true     # 表示將自己的IP註冊到Eureka Serverk, 如果不配置該屬性或將它改爲false,則表示註冊微服務所在操作系統的hostname到Eureka Server
    
user:
  userServiceUrl: http://localhost:8080/
  userEurekaService: http://cloud-service    
  userEurekaName: cloud-service    

        3) 主程序
package com.itmuch.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient   // 或@EnableDiscoveryClient
public class CloudConsumerApplication {

	@Bean  // 等價於 RestTemplate restTemplate = new RestTemplate();
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
	
	public static void main(String[] args) {
		SpringApplication.run(CloudConsumerApplication.class, args);
	}
	
}

        4) User Entntiy 類
package com.itmuch.cloud;

import java.io.Serializable;
import java.math.BigDecimal;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	private Long id;
	
	private String username;
	
	private String name;
	
	private Integer age;
	
	private BigDecimal balance;

	public Long getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public BigDecimal getBalance() {
		return balance;
	}

	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}
	
}

        5) Controller 控制層
package com.itmuch.cloud;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.ServiceInstance;

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 {
	
	@Value("${user.userServiceUrl}")   // 在yml文件中已經配置, 解決它的硬編碼問題
	private String userServiceUrl;
	
	@Value("${user.userEurekaService}")
	private String userEurekaService;
	
	@Value("${user.userEurekaName}")    
	private String userEurekaName;

	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	/**
	 * 基於Spring Boot方式來調用服務
	 * 
	 * 說明:在Spring 4.3規則中,@GetMapping等價於@RequestMapping(method = RequestMethod.GET), 用於簡化, 同理還有@PostMapping, @PutMapping, @DeleteMapping, @PatchMapping等
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/user/{id}")  
	public User findById(@PathVariable Long id) {
		return this.restTemplate.getForObject(this.userServiceUrl + id, User.class);
	}
	
	/**
	 * #1 第一種   基於Eureka服務方式來調用 
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/eureka/{id}")  
	public User findByIdEureka(@PathVariable Long id) {
		User user = this.restTemplate.getForObject("http://cloud-service/get/" + 1, User.class);
		return user;
	}
	
	/**
	 * #2 第二種   基於Eureka服務方式來調用 
	 * 
	 * @param id
	 * @return
	 * @throws MalformedURLException 
	 */
	@GetMapping("/discovery/{id}")  
	public Object findByIdDiscovery(@PathVariable Long id) throws Exception {
		// 非配置 IP 端口
		// 通過服務名獲取實例 
		// Eureka 會緩存, 不是每個請求都會調用 EurekaServer接口
		List<ServiceInstance> instances = discoveryClient.getInstances(this.userEurekaName);
		
		// 獲取到一個服務器列表,如1.2.3
		// 隨機、輪詢, ribbon客戶端負責均衡
		// 熔斷  Hystrix
		ServiceInstance serviceInstance = instances.get(0);
		
		String host = serviceInstance.getHost();
		int port = serviceInstance.getPort();
		
		URL url = new URL("http://" + host + ":" + port + "/get/" + id);
		byte[] result = new byte[3];
		InputStream input = url.openStream();
		IOUtils.readFully(input, result);
		
		System.out.println(new String(result));
		
		return new String(result);
	}
	
}



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