1. 程式人生 > >二、SpringCloud五大神獸之Eureka(服務註冊與發現)

二、SpringCloud五大神獸之Eureka(服務註冊與發現)

 ps:此工程為服務提供者叢集的建立並且註冊到eureka中,同時測試服務的發現,由於主要講解eureka知識,因此本例中一些其餘資料庫操作等例子不一一指出,在系列文章結尾會提供完整版例子下載。

1、pom檔案編寫:

<dependencies>
		<!-- 引入自己定義的api通用包,可以使用Dept部門Entity -->
		<dependency>
			<groupId>com.zhanghf</groupId>
			<artifactId>microservisecloud-api</artifactId>
			<version>${project.version}</version>
		</dependency>
		<!-- actuator監控資訊完善 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- 將微服務provider側註冊進eureka -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jetty</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>
		<!-- 修改後立即生效,熱部署 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>

	</dependencies>

2、application.yml配置檔案編寫:

2.1、服務提供者8001配置檔案:

server:
  port: 8001

mybatis:
  config-location: classpath:mybatis/mybatis.xml        # mybatis配置檔案所在路徑
  type-aliases-package: com.zhanghf.springcloud.entities    # 所有Entity別名類所在包
  mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper對映檔案

spring:
   application:
    name: microservicecloud-dept
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 當前資料來源操作型別
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驅動包
    url: jdbc:mysql://localhost:3306/clouddb01              # 資料庫名稱
    username: root
    password:
    dbcp2:
      min-idle: 5                                           # 資料庫連線池的最小維持連線數
      initial-size: 5                                       # 初始化連線數
      max-total: 5                                          # 最大連線數
      max-wait-millis: 200                                  # 等待連接獲取的最大超時時間

eureka:
  client: #客戶端註冊進eureka服務列表內
    service-url:
#      defaultZone: http://localhost:7001/eureka  單機
       defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  #叢集
#在eureka介面使微服務提供者顯示更直觀:顯示名稱和ip
  instance:
    instance-id: microservicecloud-dept8001
    prefer-ip-address: true     #訪問路徑可以顯示IP地址

#eureka伺服器中註冊的服務的info頁面的顯示內容
info:
  app.name: microservicecloud
  company.name: www.zhanghf.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

 2.2、服務提供者8002配置檔案:

server:
  port: 8002

mybatis:
  config-location: classpath:mybatis/mybatis.xml        # mybatis配置檔案所在路徑
  type-aliases-package: com.zhanghf.springcloud.entities    # 所有Entity別名類所在包
  mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper對映檔案

spring:
   application:
    name: microservicecloud-dept
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 當前資料來源操作型別
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驅動包
    url: jdbc:mysql://localhost:3306/clouddb02              # 資料庫名稱
    username: root
    password:
    dbcp2:
      min-idle: 5                                           # 資料庫連線池的最小維持連線數
      initial-size: 5                                       # 初始化連線數
      max-total: 5                                          # 最大連線數
      max-wait-millis: 200                                  # 等待連接獲取的最大超時時間

eureka:
  client: #客戶端註冊進eureka服務列表內
    service-url:
#      defaultZone: http://localhost:7001/eureka  單機
       defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  #叢集
  instance:
    instance-id: microservicecloud-dept8002
    prefer-ip-address: true     #訪問路徑可以顯示IP地址

#eureka伺服器中註冊的服務的info頁面的顯示內容
info:
  app.name: microservicecloud
  company.name: www.zhanghf.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

2.3、服務提供者8003配置檔案:

server:
  port: 8003

mybatis:
  config-location: classpath:mybatis/mybatis.xml        # mybatis配置檔案所在路徑
  type-aliases-package: com.zhanghf.springcloud.entities    # 所有Entity別名類所在包
  mapper-locations: classpath:mybatis/mapper/**/*.xml                       # mapper對映檔案

spring:
   application:
    name: microservicecloud-dept
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 當前資料來源操作型別
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驅動包
    url: jdbc:mysql://localhost:3306/clouddb03              # 資料庫名稱
    username: root
    password:
    dbcp2:
      min-idle: 5                                           # 資料庫連線池的最小維持連線數
      initial-size: 5                                       # 初始化連線數
      max-total: 5                                          # 最大連線數
      max-wait-millis: 200                                  # 等待連接獲取的最大超時時間

eureka:
  client: #客戶端註冊進eureka服務列表內
    service-url:
#      defaultZone: http://localhost:7001/eureka  單機
       defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  #叢集
  instance:
    instance-id: microservicecloud-dept8003
    prefer-ip-address: true     #訪問路徑可以顯示IP地址

#eureka伺服器中註冊的服務的info頁面的顯示內容
info:
  app.name: microservicecloud
  company.name: www.zhanghf.com
  build.artifactId: $project.artifactId$
  build.version: $project.version$

注意:提供者的叢集配置需要注意點主要就在配置檔案中。第一位各個埠要唯一;第二為spring: application: name: microservicecloud-dept要一致,因為eureka中就是通過這個名稱來識別微服務,此3個提供者為一個叢集,因此用統一的名稱;第三個為defaultZone指向的也為eurekaserver的叢集地址,有3個,如果eureka為單機的話指定一個即可。

3、controller實現:

package com.zhanghf.springcloud.controller;


import com.zhanghf.springcloud.entities.Dept;
import com.zhanghf.springcloud.service.DeptService;
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.*;

import java.util.List;

@RestController
public class DeptController
{
	@Autowired
	private DeptService service;
	@Autowired
	private DiscoveryClient client;

	@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
	public boolean add(@RequestBody Dept dept)
	{
		return  service.add(dept);
	}

	@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
	public Dept get(@PathVariable("id") Long id)
	{
		return service.get(id);
	}

	@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
	public List<Dept> list()
	{
		return  service.list();
	}

	/**
	 * 自測服務發現
	 * @return
	 */
	//	@Autowired
//	private DiscoveryClient client;
	@RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
	public Object discovery()
	{
		List<String> list = client.getServices();
		System.out.println("**********" + list);

		List<ServiceInstance> srvList = client.getInstances("MICROSERVICECLOUD-DEPT");
		for (ServiceInstance element : srvList) {
			System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
					+ element.getUri());
		}
		return this.client;
	}


}

4、啟動類中新增@EnableEurekaClient和@EnableDiscoveryClient註解,後一個為服務發現註解,不需要的話可以不用

package com.zhanghf.springcloud;

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

@SpringBootApplication
@EnableEurekaClient //本服務啟動後會自動註冊進eureka服務中
@EnableDiscoveryClient //服務發現,(作為了解)Euraka的服務註冊於發現
public class MicroservisecloudProviderDept8001Application {

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

執行測試: