SpringCloud學習之Feign 的使用(五)


 Feign 是一個聲明式的偽RPC的REST客戶端,它用了基於接口的注解方式,很方便的客戶端配置,剛開始使用時還不習慣,感覺是在客戶端寫服務端的代碼,Spring Cloud 給 Feign 添加了支持Spring MVC注解,並整合Ribbon及Eureka進行支持負載均衡。

Feign的使用很簡單,有以下幾步:

1、添加依賴

2、啟動類添加 @EnableFeignClients 注解支持

3、建立Client接口,並在接口中定義需調用的服務方法

4、使用Client接口。

 

具體如下首先先添加feign需要的依賴

1、添加 spring-cloud-starter-openfeign 依賴

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>


      完整的 pom.xml

<?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.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.xu</groupId> <artifactId>service-consumer-feign</artifactId> <version>0.0.1-SNAPSHOT</version> <name>service-consumer-feign</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.M3</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.48</version> </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> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> </project> 

2、啟動類添加 @EnableFeignClients 注解支持

package com.xu.serviceconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceConsumerFeignApplication {

    public static void main(String[] args) {

        SpringApplication.run(ServiceConsumerFeignApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {

        return new RestTemplate();
    }
}


3、建立Client接口,並在接口中定義需調用的服務方法

package com.xu.serviceconsumer.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "service-hello")
public interface UserFeignClient {

    @RequestMapping(value="/hi",method = RequestMethod.GET)
    String getName(@RequestParam String name);

}


    說明:>> name="service-hello",這里的"service-hello"是注冊到Eureka 中的要調用的應用名

                >> @GetMapping("/hi") 這里的“/hi”是要調用的應用里的相應的方法(這里需注意,如果service-hello服務下面的                                  訪問路徑是 /hi/hello ,則這里也要寫"/hi/hello")。

 

4、使用Client接口

 

package com.xu.serviceconsumer.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.xu.serviceconsumer.service.HelloService;
import com.xu.serviceconsumer.service.UserFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloControler {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloControler.class);

    @Autowired
    private HelloService helloService;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @RequestMapping(value = "/hi")
    public String hi(@RequestParam String name) {

        return helloService.hiService(name);
    }

    @RequestMapping(value = "/hello")
    public String hello(@RequestParam String name) {

        return userFeignClient.getName(name);
    }

    @RequestMapping(value = "/log-instance")
    public Object logInstance() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("SERVICE-HELLO");
        LOGGER.info("{}:{}:{}", serviceInstance.getServiceId(),
                serviceInstance.getHost(),serviceInstance.getPort());

        JSONObject object1 = new JSONObject();
        object1.put("ServiceId",serviceInstance.getServiceId());
        object1.put("Host",serviceInstance.getHost());
        object1.put("Port",serviceInstance.getPort());
        return object1.toJSONString();
    }

}

打開瀏覽器,訪問上面Controller中的RestApi請求http://localhost:8767/hello?name=Ronnie結果如下:

 
看到這里顯然我們的請求響應成功了,成功調用了服務提供者的服務,本節課程到此就結束了,各位如有疑問請再下方留言,我會盡快答復,謝謝觀賞!

===============================================================================

如果您覺得此文有幫助,可以打賞點錢給我支付寶或掃描二維碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM