最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)類啟用FeignClients

在orderService的啟動(dòng)類中通過(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ù)名稱,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接口是否很類似?

對(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)文章

最新評(píng)論

时尚| 中超| 明溪县| 多伦县| 芦溪县| 渭南市| 酒泉市| 济源市| 乐亭县| 交城县| 南平市| 大城县| 西丰县| 白水县| 磐安县| 宁化县| 齐河县| 天峻县| 江安县| 奉化市| 遂昌县| 房山区| 诏安县| 罗平县| 沁源县| 高州市| 鸡东县| 鄄城县| 佛冈县| 南投市| 白山市| 庄浪县| 慈利县| 文昌市| 宜春市| 白沙| 岑巩县| 关岭| 湖南省| 赣榆县| 青州市|