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

Spring cloud無(wú)縫集成Feign的使用示例詳解

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

Feign的作用

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

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.

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

為什么要使用Feign

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

但是不管是誰(shuí),我們項(xiàng)目中都需要一個(gè)比RestTemplate更加靈活的Web客戶端組件。因?yàn)镽estTemplate使用起來(lái)確實(shí)非常不方便:

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)用中會(huì)有很多地方需要調(diào)用微服務(wù)userservice的接口,每一個(gè)調(diào)用的地方都需要寫(xiě)url,代碼會(huì)顯得非常凌亂、不優(yōu)雅、不易維護(hù)。

Feign可以完美解決以上RestTemplate的問(wèn)題,尤其是Spring Cloud整合Eureka和Spring LoadBalancer之后,還可以輕松實(shí)現(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啟動(dòng)類(lèi)啟用FeignClients

在orderService的啟動(dòng)類(lèi)中通過(guò)@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就可有可無(wú)了,無(wú)需理會(huì)。

編寫(xiě)FeignClient接口

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

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

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

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

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

回想一下MyBatis,和Mapper接口是否很類(lèi)似?

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

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

@Service
@Slf4j
public class OrderService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IUserService userService;
    public String getOrder(){
        //通過(guò)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();
    }
}

測(cè)試

分別啟動(dòng)Eureka模塊、orderservice模塊、userservice模塊:

瀏覽器訪問(wèn)測(cè)試:

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

反復(fù)刷新訪問(wèn):

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

在使用RestTemplate作為WEB客戶端的時(shí)候,我們需要通過(guò)@LoadBalanced注解來(lái)啟用Spring LoadBalancer負(fù)載均衡,但是FeignClient并不需要做什么,自動(dòng)集成了負(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使其超時(shí):

@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;
    }
}

前端訪問(wèn)驗(yàn)證:

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


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

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

以上就是Spring cloud無(wú)縫集成Feign的使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Spring cloud無(wú)縫集成Feign的資料請(qǐng)關(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()來(lái)更新數(shù)據(jù)時(shí),無(wú)法將字段設(shè)置為null值,更新后數(shù)據(jù)還是原來(lái)的值,本文就來(lái)詳細(xì)的介紹一下解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-08-08
  • mybatis的Configuration詳解

    mybatis的Configuration詳解

    這篇文章主要介紹了mybatis的Configuration詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(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)控,并通過(guò)Grafana展示監(jiān)控?cái)?shù)據(jù)
    2024-12-12
  • SpringBoot?實(shí)現(xiàn)全局異常處理的示例代碼

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

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

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

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

    mybatis-plus批量更新updateBatchById問(wèn)題

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

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

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

    JAVA 深層拷貝 DeepCopy的使用詳解

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

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

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

最新評(píng)論