欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring cloud無縫集成Feign的使用示例詳解

 更新時間:2023年12月21日 14:25:28   作者:福  
這篇文章主要為大家介紹了Spring cloud無縫集成Feign的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

Feign的作用

Feign是Netflix公司開發(fā)的聲明式web客戶端組件,Spring對Feign做了無縫集成:

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Eureka, as well as Spring Cloud LoadBalancer to provide a load-balanced http client when using Feign.

可以通過Feign注解或JAX-RS注解使用,F(xiàn)eign也支持拔插式的編解碼。Spring Cloud增加了對Spring MVC注解的支持,并且在SpringMVC項目中默認(rèn)使用HttpMessageConverters 轉(zhuǎn)換器。同時,Spring Cloud集成了Eureka、Spring Cloud LoadBalancer等組件,以提供在使用Feign組件時的負(fù)載均衡。

為什么要使用Feign

由于Spring6.0之后有了自己的Web客戶端組件,所以在Spring Cloud2022之后,Spring官方其實是在逐步的移除Feign、而使用自己的Web客戶端組件作為替代。

但是不管是誰,我們項目中都需要一個比RestTemplate更加靈活的Web客戶端組件。因為RestTemplate使用起來確實非常不方便:

public User getUserByRestTemplate(){
        String url="http://userservice/user/getUser";
        System.out.println("url"+url);
//        int c = 1/0;
        return restTemplate.getForObject(url,User.class);

    }

應(yīng)用中會有很多地方需要調(diào)用微服務(wù)userservice的接口,每一個調(diào)用的地方都需要寫url,代碼會顯得非常凌亂、不優(yōu)雅、不易維護(hù)。

Feign可以完美解決以上RestTemplate的問題,尤其是Spring Cloud整合Eureka和Spring LoadBalancer之后,還可以輕松實現(xiàn)負(fù)載均衡。

Feign的使用

pom文件引入openfeign

我們以前面幾篇文章的案例為基礎(chǔ),在Eureka、Spring LoadBalancer、Hystrix框架基礎(chǔ)上搭建Feign。

首先在orderservice模塊下,pom文件引入openFeign:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springCloud</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>orderservice</artifactId>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>userService</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
</project>

orderService啟動類啟用FeignClients

在orderService的啟動類中通過@EnableFeignClients注解啟用FeignClient:

package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@EnableFeignClients
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class);
    }
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

RestTemplate就可有可無了,無需理會。

編寫FeignClient接口

創(chuàng)建一個接口文件UserService

@FeignClient(name="userservice",path="/user")
public interface IUserService {
    @GetMapping("/getUser")
    public User getUser();
}

通過@FeignClient注解,指定當(dāng)前接口是一個FeignClient的接口文件,其中name屬性指定其對應(yīng)的微服務(wù)名稱,path指定對該服務(wù)的訪問路徑。

接口方法支持SpringMVC的注解,比如@GetMapping、@PostMapping等等,相當(dāng)于是在訪問當(dāng)前服務(wù)下的Controller方法一樣。這為程序員在微服務(wù)環(huán)境下的服務(wù)調(diào)用提供了極大的方便,使得微服務(wù)調(diào)用變的輕而易舉。

尤其,這個接口是不需要我們?nèi)崿F(xiàn)的,由Feign在Spring Cloud服務(wù)啟動過程中通過代理實現(xiàn)并自動注入到Spring Ioc容器中。所以我們在應(yīng)用中可以直接通過自動裝配引用。

回想一下MyBatis,和Mapper接口是否很類似?

對接口方法的調(diào)用

找到我們以前通過RestTemplate調(diào)用userservice服務(wù)的應(yīng)用,通過@AutoWired注解自動裝配IUserService ,直接調(diào)用接口方法getUser():

@Service
@Slf4j
public class OrderService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IUserService userService;
    public String getOrder(){
        //通過userService獲取user信息
//        User user = getUserByRestTemplate();
        User user = getUserByFeign();
//        System.out.println(user);
        return user.getName();
    }
    public User getUserByRestTemplate(){
        String url="http://userservice/user/getUser";
        System.out.println("url"+url);
//        int c = 1/0;
        return restTemplate.getForObject(url,User.class);
    }
    public User getUserByFeign(){
        return userService.getUser();
    }
}

測試

分別啟動Eureka模塊、orderservice模塊、userservice模塊:

瀏覽器訪問測試:

說明Feign已經(jīng)正常工作。

反復(fù)刷新訪問:

說明Spring LoadBalancer已經(jīng)正常工作。

在使用RestTemplate作為WEB客戶端的時候,我們需要通過@LoadBalanced注解來啟用Spring LoadBalancer負(fù)載均衡,但是FeignClient并不需要做什么,自動集成了負(fù)載均衡。

集成Hystrix

orderService服務(wù)的Controller中增加@HystrixCommand配置:

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    FallbackHandle fallbackHandle;
    @GetMapping("/getOrder")
    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String getOrder(){
        log.info("Come here to get Order....123===");
        return orderService.getOrder();
    }
    public String fallback(){
        return "orderService服務(wù)異常";
    }
}

然后userservice的getUser方法添加sleep使其超時:

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Value("${server.port}")
    private String serverPort;
    @GetMapping("/getUser")
    @HystrixCommand(fallbackMethod = "fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "8000")
    })
    public User getUser(){
        log.info("userController's getuser comming......");
        User user=new User();
        user.setName("zhangsan from:"+serverPort);
        try{
            log.info("I am sleepint for 10 second");
            Thread.sleep(10*1000);
            log.info("I weekup");
        }catch (Exception e){
        }
        return user;
    }
    public User fallback(){
        User user=new User();
        user.setName("userService服務(wù)異常");
        return user;
    }
}

前端訪問驗證:

如果修改userService的@HystrixCommand超時時長參數(shù)為2秒,則:


說明Hystrix組件已經(jīng)可以正常工作,與Feign組件進(jìn)行了無縫集成。

Spring cloud feign官網(wǎng):https://cloud.spring.io/spring-cloud-openfeign/reference/html...

以上就是Spring cloud無縫集成Feign的使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Spring cloud無縫集成Feign的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Spring中@Transactional注解的使用詳解

    Spring中@Transactional注解的使用詳解

    @Transactional注解是Spring提供的一種聲明式事務(wù)管理方式,這篇文章主要為大家詳細(xì)介紹了@Transactional注解的原理分析及使用,需要的可以參考一下
    2023-05-05
  • MyBatis-Plus updateById不更新null值的方法解決

    MyBatis-Plus updateById不更新null值的方法解決

    用Mybatis-Plus的updateById()來更新數(shù)據(jù)時,無法將字段設(shè)置為null值,更新后數(shù)據(jù)還是原來的值,本文就來詳細(xì)的介紹一下解決方法,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • mybatis的Configuration詳解

    mybatis的Configuration詳解

    這篇文章主要介紹了mybatis的Configuration詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • 使用Prometheus監(jiān)控Tomcat等java應(yīng)用的狀態(tài)

    使用Prometheus監(jiān)控Tomcat等java應(yīng)用的狀態(tài)

    本文介紹了如何配置Tomcat監(jiān)控,使用JMX Exporter和Prometheus進(jìn)行監(jiān)控,并通過Grafana展示監(jiān)控數(shù)據(jù)
    2024-12-12
  • SpringBoot?實現(xiàn)全局異常處理的示例代碼

    SpringBoot?實現(xiàn)全局異常處理的示例代碼

    本文主要介紹了SpringBoot實現(xiàn)全局異常處理,全局異常處理器的使用可以顯著提高Spring Boot項目的代碼質(zhì)量和可維護(hù)性,減少冗余代碼,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06
  • Java設(shè)計模式以虹貓藍(lán)兔的故事講解橋接模式

    Java設(shè)計模式以虹貓藍(lán)兔的故事講解橋接模式

    橋接是用于把抽象化與實現(xiàn)化解耦,使二者可以獨立變化。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式,它通過提供抽象化和實現(xiàn)化之間的橋接結(jié)構(gòu),來實現(xiàn)二者的解耦。這種模式涉及到一個作為橋接的接口,使得實體類的功能獨立于接口實現(xiàn)類。這兩種類型的類可被結(jié)構(gòu)化改變而互不影響
    2022-04-04
  • mybatis-plus批量更新updateBatchById問題

    mybatis-plus批量更新updateBatchById問題

    這篇文章主要介紹了mybatis-plus批量更新updateBatchById問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • java正則替換sql中的參數(shù)實例代碼

    java正則替換sql中的參數(shù)實例代碼

    這篇文章主要給大家介紹了關(guān)于java正則替換sql中參數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-10-10
  • JAVA 深層拷貝 DeepCopy的使用詳解

    JAVA 深層拷貝 DeepCopy的使用詳解

    最近需要用到比較兩個對象屬性的變化,其中一個是oldObj,另外一個是newObj,oldObj是newObj的前一個狀態(tài),所以需要在newObj的某個狀態(tài)時,復(fù)制一個一樣的對象,由于JAVA不支持深層拷貝,因此專門寫了一個方法
    2013-07-07
  • 解析WeakHashMap與HashMap的區(qū)別詳解

    解析WeakHashMap與HashMap的區(qū)別詳解

    本篇文章是對WeakHashMap與HashMap的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05

最新評論