Spring Cloud 入門教程(一):erureka 搭建-註冊-發現服務

1.  什麼是Spring Cloud?

Spring提供了一系列工具,可以幫助開發人員迅速搭建分佈式系統中的公共組件(比如:配置管理,服務發現,斷路器,智能路由,微代理,控制總線,一次性令牌,全局鎖,主節點選舉, 分佈式session, 集羣狀態)。協調分佈式環境中各個系統,爲各類服務提供模板性配置。使用Spring Cloud, 開發人員可以搭建實現了這些樣板的應用,並且在任何分佈式環境下都能工作得非常好,小到筆記本電腦, 大到數據中心和雲平臺。

Spring Cloud官網的定義比較抽象,我們可以從簡單的東西開始。Spring Cloud是基於Spring Boot的, 最適合用於管理Spring Boot創建的各個微服務應用。要管理分佈式環境下的各個Spring Boot微服務,必然存在服務的註冊問題。所以我們先從服務的註冊談起。既然是註冊,必然有個管理註冊中心的服務器,各個在Spring Cloud管理下的Spring Boot應用就是需要註冊的client

Spring Cloud使用erureka server,  然後所有需要訪問配置文件的應用都作爲一個erureka client註冊上去。eureka是一個高可用的組件,它沒有後端緩存,每一個實例註冊之後需要向註冊中心發送心跳,在默認情況下erureka server也是一個eureka client ,必須要指定一個 server。

2.項目採用maven聚合工程 用spring boot 搭建 spring cloud的微服務 模塊式開發:

                                                               

       2.1創建聚合工程的父模塊

                                                    

       2.2設置父模塊的POM文件(沒有管理版本):

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.guo</groupId>
    <artifactId>springCloud-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
</project>

3.創建Eureka Server

    3.1創建 Eureka server

          3.2 引入子模塊pom。

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<groupId>com.guo</groupId>
	<artifactId>eureka-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>eureka-server</name>
	<packaging>war</packaging>
	<description>Demo project for Spring Boot</description>

	<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>Finchley.RELEASE</spring-cloud.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <!--eureka server安全認證 -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-security</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>

     子模塊管理到父pom中(可以省略)

   <!-- 子模塊 -->
    <modules>
        <module>eureka-server</module>
    </modules>

     3.3 在application.yml中加入配置

                                      

       application.yml

spring:
  application:
    name: boot-eureka
    #不想讓所有人都能訪問到eurekaserver的界面,可以加上權限認證
  security:
    user:
        name: admin
        password: 123456
  profiles:
    #指向開發環境的yml文件
    active: dev

       application-dev.yml

server:
  port: 8081
eureka:
  instance:
    hostname: localhost
  server:  #配置屬性,但由於 Eureka 自我保護模式以及心跳週期長的原因,經常會遇到 Eureka Server 不剔除已關停的節點的問題
    enable-self-preservation: false
    eviction-interval-timer-in-ms: 5000
    peer-eureka-nodes-update-interval-ms: 1000
    wait-time-in-ms-when-sync-empty: 0
  # 不向註冊中心註冊自己
  client:
    fetch-registry: false
    register-with-eureka: false
    eureka-server-total-connections: 200
    serviceUrl:
    #添加認證密碼,用戶名
      defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/

         3.4 修改啓動類加註解:@EnableEurekaServer

package com.guo.eurekaserver;

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

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

}

      3.5報錯無法註冊到eureka-server,新版本的security默認開啓csrf了,添加一個文件(建在啓動類裏面)關掉就好了。

package com.guo.eurekaserver;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); // 關閉csrf
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); // 開啓認證
    }

}

啓動eureka server,然後訪問http://localhost:10086/eureka, 界面如下, "No instances available" 表示無client註冊

 

4.  創建Eureka Client

   4.1  用spring boot創建子工程

   4.2.  創建主類EurekaClientApplication,使用@EnableEurekaClient註解表明是client

package com.guo.eurekaclient;

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

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientApplication {

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

}

     4.3 eureka client的配置文件application.yml

spring:
  application:
    name: boot-service
  profiles:
    active: dev

     application-dev.yml

server:
  port: 9081
spring:
  application:
    name: client-a
eureka:
  client:
    serviceUrl:
    #添加認證用戶名,密碼
      defaultZone: http://admin:[email protected]:8081/eureka/

   4.4  寫一個接口

    

package com.guo.service.impl;

import com.guo.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    public String getUser(){

        return "hello world!";
    }
}
package com.guo.controller;

import com.guo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/getUser")
    public String getUser(){
        return userService.getUser();
    }
}

    4.5 Client啓動後, 可以訪問http://localhost:8762

 

    4.6 如果訪問不到,檢查啓動類是否在最外層資源包裏面

 

5.創建Eureka 消費者(服務的調用者)

  5.1  創建consumer項目(同4.1,與服務註冊一樣)

  5.2  pom,application.yml文件(跟服務註冊一樣)

  5.3  啓動類加入 RestTemplate

package com.guo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class EurekaConsumer2Application {

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

	@Bean
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

   5.4  controller 層調用

package com.guo.controller;

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

@RestController
public class GetUserController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/user")
    public String userString() {
        String str = restTemplate.getForObject("http://localhost:9081/getUser", String.class);
        return str;
    }
}

  5.5  restTemplate返回類型:string.class  vo.class 扥類型。

 

  5.6 調用consumer的方法http://localhost:10082/user,成功後的結果:

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