springcloud服務與服務之間的調用(Feign)

  • springcloud是什麼?

           Spring Cloud爲開發人員提供了快速構建分佈式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智能路由,控制總微代理,線,一次性令牌,全局鎖定,領導選舉,分佈式會話,集羣狀態)。分佈式系統的協調導致鍋爐板模式,使用Spring Cloud開發人員可以快速站起來實現這些模式的服務和應用程序。它們適用於任何分佈式環境,包括開發人員自己的筆記本電腦,裸機數據中心和Cloud Foundry等託管平臺。

  • 什麼分佈式系統?

         分佈式就是將一個系統拆分成很多的子系統,比如淘寶系統,他有許許多多的子系統:會員系統、訂單系統、積分系統等等,這樣已拆分就大大的減輕了服務器的壓力,如果想深入瞭解分佈式的架構,還請百度分佈式架構,這裏不多做說明。

  • 什麼是Feign

          既然一個系統被拆分成了無數個子系統,那系統之間是如何進行通信的呢?假如我現在在訂單系統中想獲取到會員的信息,此時,你能怎麼做?

          可能你會說用外鏈接查詢,這個也沒啥錯,但是正規的分佈式系統都是將對應的表分給了對應的庫,所以這裏鏈接查詢是走不通的,這時,你可能在想,要是我能直接調用會員服務的方法那該多好,Feign就來了,他解決了服務與服務之間的通訊。

          Feign是一種聲明式、模板化的HTTP客戶端。在Spring Cloud中使用Feign, 我們可以做到使用HTTP請求遠程服務時能與調用本地方法一樣的編碼體驗,開發者完全感知不到這是遠程方法,更感知不到這是個HTTP請求,類似於Dubbo的RPC。

  •  eureka

        如果想實現服務與服務之前的調用,那麼必須要有eureka這個註冊中心,eureka在這裏不多做解釋,直接看代碼:

      1.創建一個eureka-service的springboot項目。

                    
       2.maven依賴:     

<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.ymy</groupId>
	<artifactId>sprintcloud</artifactId>
	<version>0.0.1-SNAPSHOT</version>

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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>
        <!--eureka server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <!-- spring boot test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</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>
    <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>

不需要的jar可以不引用。

3.添加配置文件:

server:
  port: 8769
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

這樣eureka服務算是大功告成。

  • 服務端1(被調用端1)

      創建一個springboot項目:

                     

       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.ymy.client1</groupId>
  <artifactId>cloud-client1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>boot1</name>
	<description>Demo project for Spring Boot</description>
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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</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>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</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>
    <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>

    新建配置文件:application.yml

       

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8769/eureka/
server:
  port: 8762
spring:
  application:
    name: service-hi

啓動類:我將controller直接寫在了啓動類了,你們可以新建一個controller包

package com.ymy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@EnableEurekaClient
@SpringBootApplication
@RestController
@RequestMapping("c")
public class App1 {
	
	public static void main(String[] args) {
		SpringApplication.run(App1.class, args);
	}
	
	@Value("${server.port}")
	String port;
	@GetMapping("hello")
	public String hello(@RequestParam String name){
		
		return "hello "+name+" 我的服務端口是:"+port;
	}
}
  • 服務端2(被調用端2)

      新建一個springboot項目:

           

        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.ymy.client1</groupId>
  <artifactId>cloud-client1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.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</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>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</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>
    <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>

新建配置文件:application.yml

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8769/eureka/
server:
  port: 8763
spring:
  application:
    name: service-hi

啓動類:

    

package com.ymy;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@EnableEurekaClient
@SpringBootApplication
@RestController
@RequestMapping("c")
public class App2 {
	
	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);
	}
	
	@Value("${server.port}")
	String port;
	@GetMapping("hello")
	public String hello(@RequestParam String name){
		
		return "hello "+name+" 我的服務端口是:"+port;
	}
}
  • 客服端(調用端)

新建一個springboot項目

     

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.ymy.client3</groupId>
	<artifactId>cloud-client3</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.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</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</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>
			<scope>test</scope>
		</dependency>
		<!-- 斷路器 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Dalston.RC1</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>

	<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>

 

新建application.yml文件
    

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8769/eureka/
server:
  port: 8765
spring:
  application:
    name: service-feign
feign:
  hystrix:
    enabled: true

controller類:

package com.ymy.controller;

import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ymy.feign.ClientFeign;
import com.ymy.feign.HystrixClientFeign;
@RestController
public class MyController {

	@Inject
	private ClientFeign clientFeign;
//	@Autowired
//	private HystrixClientFeign hystrixClientFeign;
	
	
	@GetMapping("hi")
	public String hi(@RequestParam String name){
		return clientFeign.getHello(name);
	}
	
	/*@GetMapping("hihi")
	public String hihi(@RequestParam String name){
		System.out.println("哈哈哈哈");
		return hystrixClientFeign.hello(name);
	}*/
}

重點來了,Feign的運用:

ClientFeign類:

package com.ymy.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;


@FeignClient(value = "service-hi", fallback = HystrixClientFeign.class)
public interface ClientFeign {
	@GetMapping("c/hello")
	String getHello(@RequestParam(value = "name") String name);
}

HystrixClientFeign類:

  

package com.ymy.feign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Component
public class HystrixClientFeign implements ClientFeign{

//	@Autowired
//	private RestTemplate  restTemplate;
	
	
//	@HystrixCommand(defaultFallback="hiError")
//	public String hello(String name){
//		return restTemplate.getForObject("http://service-hi/hello?name="+name, String.class);
//	}
	
	/*public String hiError(String name) {
        return "hi," + name + ",sorry,error!";
    }*/

	@Override
	public String getHello(String name) {
		return "hello " + name + ", error!";
	}
}

代碼已經貼的差不多了,下面我們來看運行結果:

 

兩個服務端我做的是集羣,客服端以輪詢的方式訪問,有興趣的小夥伴可以試試哦,需要源碼的可以留言哦。

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