溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringCloud?OpenFeign如何實(shí)現(xiàn)

發(fā)布時(shí)間:2023-02-22 09:31:00 來源:億速云 閱讀:112 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“SpringCloud OpenFeign如何實(shí)現(xiàn)”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“SpringCloud OpenFeign如何實(shí)現(xiàn)”文章能幫助大家解決問題。

常用注解

OpenFeign是使用接口+注解實(shí)現(xiàn)的,因此了解它的常用注解是必要的,有以下幾個(gè):

@EnableFeignClients:在啟動(dòng)類上添加,用于開啟OpenFeign功能。當(dāng)項(xiàng)目啟動(dòng)時(shí),會(huì)掃描帶有@FeignClient的接口,生成代理類并注冊(cè)到Spring容器中

@FeignClient:通知OpenFeign組件對(duì)該注解下的接口進(jìn)行解析,通過動(dòng)態(tài)代理的方式產(chǎn)生實(shí)現(xiàn)類,完成服務(wù)調(diào)用

@RequestMapping:SpringMvc中的注解,不過此時(shí)該注解表示發(fā)起Request請(qǐng)求(默認(rèn)Get方式)

@GetMapping:SpringMvc中的注解,不過此時(shí)該注解表示發(fā)起Get請(qǐng)求

@PostMapping:SpringMvc中的注解,不過此時(shí)該注解表示發(fā)起Post請(qǐng)求

代碼實(shí)現(xiàn)

首先得把Nacos啟動(dòng)

服務(wù)提供方,

bootstrap.yml:

server:
  port: 8083
  servlet:
    context-path: /nacosProvider

spring:
  application:
    name: nacos-provider
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

引入依賴:

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery
        </artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

服務(wù)方法:

@Controller
@RequestMapping("/provide")
public class ProviderController {
    @RequestMapping("/distribute")
    @ResponseBody
    public String distribute() {
        return "吃雞胸肉";
    }
    @RequestMapping("/distribute1")
    @ResponseBody
    public String distribute1(String name, Integer age) {
        return "姓名:" + name + ",年齡:" + age;
    }
    @PostMapping("/distribute2")
    @ResponseBody
    public String distribute2(@RequestBody Person p) {
        return "身高:" + p.getHeight() + ",膚色:" + p.getSkin();
    }
}
import lombok.Data;
@Data
public class Person {
    private Integer height;
    private String skin;
}

服務(wù)調(diào)用方,

bootstrap.yml

server:
  port: 8082
  servlet:
    context-path: /nacosInvoke

spring:
  application:
    name: nacos-invoke
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

引入依賴:

<dependencies>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery
        </artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

啟動(dòng)類上添加注解:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
//開啟OpenFeign
@EnableFeignClients
@SpringBootApplication
public class NacosInvokeApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConfigApplication.class, args);
    }
}

創(chuàng)建@FeignClient修飾的接口:

import com.gs.nacos_invoke.dto.Person;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * value值是服務(wù)提供方的服務(wù)名稱
 */
@FeignClient(value = "nacos-provider")
public interface InvokeClient {
    @GetMapping("/nacosProvider/provide/distribute")
    String distribute();
    @GetMapping("/nacosProvider/provide/distribute1")
    String distribute1(@RequestParam("name") String name, 
    @RequestParam("age") Integer age);
    @PostMapping("/nacosProvider/provide/distribute2")
    String distribute2(@RequestBody Person p);
}

Person類(服務(wù)調(diào)用方再創(chuàng)建一個(gè),不是同一個(gè)):

import lombok.Data;
@Data
public class Person {
    private Integer height;
    private String skin;
}

編寫控制器,使用接口請(qǐng)求提供方的服務(wù):

import com.gs.nacos_invoke.dto.Person;
import com.gs.nacos_config.feign.InvokeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private InvokeClient invokeClient;
    @GetMapping("/invoke")
    public void invoke(String name, Integer age) {
        String str = invokeClient.distribute();
        System.out.println(str);
    }
    @GetMapping("/invoke1")
    public void invoke1() {
        String str = invokeClient.distribute1("coder", 20);
        System.out.println(str);
    }
    @GetMapping("/invoke2")
    public void invoke2() {
        Person p = new Person();
        p.setHeight(183);
        p.setSkin("黃皮膚");
        String s = invokeClient.distribute2(p);
        System.out.println(s);
    }
}

注意事項(xiàng)

OpenFeign是基于Ribbon的,所以它默認(rèn)是負(fù)載均衡的。其次,它也是基于Hystrix的,有超時(shí)降級(jí)的處理:默認(rèn)服務(wù)提供方的接口超時(shí)時(shí)間是1s,超過1s服務(wù)調(diào)用方會(huì)報(bào)錯(cuò)。1s是可以配置的,按照業(yè)務(wù)需要調(diào)整。@FeignClient注解有個(gè)fallback屬性,當(dāng)該屬性有值時(shí),服務(wù)提供方超時(shí),會(huì)返回程序所指定的降級(jí)值。

服務(wù)調(diào)用方,bootstrap.yml添加(更規(guī)范的做法是引入spring-cloud-starter-alibaba-nacos-config依賴,nacos中新建配置,然后在這個(gè)配置中添加):

feign:
  hystrix:
    enabled: true
ribbon:
    # 請(qǐng)求連接的超時(shí)時(shí)間
    ConnectionTimeout: 3000
    # 請(qǐng)求處理的超時(shí)時(shí)間
    ReadTimeout: 3000

hystrix:
    command:
        default:
            execution:
                isolation:
                    thread:
                        timeoutInMilliseconds: 3000

接口修改為:

import com.gs.nacos_invoke.dto.Person;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "nacos-provider",
        fallback = InvokeClientFallback.class)
public interface InvokeClient {
    @GetMapping("/nacosProvider/provide/distribute")
    String distribute();
    @GetMapping("/nacosProvider/provide/distribute1")
    String distribute1(@RequestParam("name") String name, 
    @RequestParam("age") Integer age);
    @PostMapping("/nacosProvider/provide/distribute2")
    String distribute2(@RequestBody Person p);
}

fallback指定的類:

import com.gs.nacos_invoke.dto.Person;
import org.springframework.stereotype.Component;
@Component
public class InvokeClientFallback implements InvokeClient {
    @Override
    public String distribute() {
        return "超時(shí)3s";
    }
    @Override
    public String distribute1(String name, Integer age) {
        return "超時(shí)3s";
    }
    @Override
    public String distribute2(Person p) {
        return "超時(shí)3s";
    }
}

服務(wù)提供方ProviderController類的方法中,加入Thread.sleep(4000);或者throw new RuntimeException("拋異常");來觸發(fā)降級(jí)(拋出未捕獲的異常也能觸發(fā))。

關(guān)于“SpringCloud OpenFeign如何實(shí)現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI