1. 程式人生 > >四、SpringCloud使用Feign實現負載均衡

四、SpringCloud使用Feign實現負載均衡

一、Feign簡介
Feign是收到了 Retrofit, JAXRS-2.0, and WebSocket啟發而產生的http客戶端。極大的簡化了restful風格的http API引數繫結。Feign預設集成了Ribbon,使用Feign可以指定編碼解碼,重請求等功能,需要進行配置
二、Feign的使用
1、建立專案consulclient4,引入依賴

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId
>
org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.0.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.M8</version> <type>pom</type> <scope
>
import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--用於監控與管理--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!--config server--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul</artifactId> </dependency> <!--服務發現依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!--用於consul配置--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency> <!--Feign的依賴--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>

2、建立Feign介面

@FeignClient("consulservice3")//依然用我們的使用過的service consulservice3
public interface SayService {

    @RequestMapping(value = "say")
    String say();
}

3、使用Feign

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients//必不可少,使用此註解才能掃描到Feign介面,負責不會注入SayService
@RestController
public class ConsulClient4App {

    @Autowired
    private SayService sayService;

    @RequestMapping("say")
    public String say(){
        return sayService.say();
    }

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

4、以埠9999啟動ConsulClient4App,呼叫介面localhost:9999/say
這裡寫圖片描述
這裡寫圖片描述

原始碼:
https://github.com/NapWells/spring_cloud_learn/tree/master/discover_server_with_consul/springcloudlearn/consulclient4