In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to use SpringCloud's OpenFeign for service invocation". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Preface
Feign is a declarative Web service client that is interface-oriented. In other words, with Feign, you only need to create an interface and configure it with annotations to complete the interface binding to the micro-service provider.
When using RestTemplate, you need to specify the specific path of the service each time you invoke the service, and when you use it in multiple places at the same time, you have to write multiple times, which makes it difficult to maintain code redundancy, which can be avoided by openfeign.
1. Overview of OpenFeign1.1 and OpenFeign
1. What is it?
Feign is a declarative web service client that makes it easy to write a web service client by creating an interface and annotating it.
Source code address
two。 What can I do?
Feign is designed to make it easier to write Java Http clients.
When using Ribbon + RestTemplate, the previous service invocation uses RestTemplate's encapsulation of http requests to form a set of templated invocation methods. However, in the actual development, because there may be more than one call to the service dependency, often an interface will be called in multiple places, so it is usually necessary to encapsulate some client classes for each micro-service to wrap these invocations. Therefore, Feign makes further encapsulation on this basis, and it helps us to define and implement the definition of dependent service interfaces. Under the implementation of Feign, we only need to create an interface and configure it with annotations (in the past, Dao interfaces were marked with Mapper annotations, but now a Feign annotation is marked on a micro-service interface) to complete the interface binding to the service provider, which simplifies the development of automatically encapsulating the service invocation client when using Spring Cloud Ribbon.
Feign integrates Ribbon, uses Ribbon to maintain the service list information of Payment, and realizes the load balancing of the client through polling. Unlike Ribbon, Feign only needs to define the service binding interface and implements the service invocation elegantly and simply in a declarative way.
3. The difference between Feign and OpenFeign
FeignOpenFeignFeign is a lightweight restful Http service client in SpringCloud components. Feign has built-in Ribbon to do client-side load balancing to invoke services in the service registry. Feign is used by using Feign's annotations to define the interface, and by calling this interface, you can invoke the service of the service registry OpenFeign. SpringCloud supports SpringMVC annotations on the basis of Feign, such as @ RequestMapping, and so on. The @ FeignClient of OpenFeign can parse the interface under the @ RequestMapping annotation of SpringMVC, and implement the class by dynamic proxy, realizing the steps of load balancing and calling other services 1.2 and OpenFeign in the class.
1. Build Module
The name of Module is cloud-consumer-feign-order80.
two。 Change to POM
Cloud02 com.xiao 1.0-SNAPSHOT 4.0.0 cloud-consumer-feign-order80 org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-eureka-client com.xiao cloud-api- Commons 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-devtools runtime true Org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test
3. Change to YML
Server: port: 80eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
4. Main start
Import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication@EnableFeignClients / / Open OpenFeignpublic class OrderFeignMain80 {public static void main (String [] args) {SpringApplication.run (OrderFeignMain80.class,args);}}
@ EnableFeignClients turn on OpenFeign
5. PaymentFeignService interface
Import com.xiao.cloud.entities.CommonResult;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.stereotype.Component;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;@Component@FeignClient (value = "CLOUD-PAYMENT-SERVICE") / / use OpenFeignpublic interface PaymentFeignService {@ GetMapping ("/ payment/get/ {id}") public CommonResult getPaymentById (@ PathVariable ("id") Long id);}
@ FeignClient (value = "CLOUD-PAYMENT-SERVICE") uses OpenFeign.
6. Controller class
Import com.xiao.cloud.entities.CommonResult;import com.xiao.cloud.entities.Payment;import com.xiao.cloud.service.PaymentFeignService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;@RestController@Slf4jpublic class PaymentFeignController {@ Autowired private PaymentFeignService paymentFeignService GetMapping ("/ consumer/payment/get/ {id}") public CommonResult getPaymentById (@ PathVariable ("id") Long id) {return paymentFeignService.getPaymentById (id);}}
7. Test result
When we click Refresh many times, the port changes in turn between 8001 and 8002.
8. Small summary
1.3, timeout control 1.3.1, what is it?
The default Feign client only waits for one second, but it takes more than 1 second for the server to process. As a result, the Feign client does not want to wait and returns an error directly. To avoid this, sometimes we need to set the timeout control for the Feign client.
Open the configuration in the yml file.
1.3.2. Timeout error in modifying code settings
1. Modify the Controller of payment module 8001
Add the following code
GetMapping (value = "/ payment/feign/timeout") public String timeOUt () {try {Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} return ServerPort;}
two。 Modify the PaymentFeignService of the order module
Add the following code
GetMapping (value = "/ payment/feign/timeout") public String timeOUt ()
3. Modify the OrderFeignController of the order module
Add the following code
GetMapping (value = "/ consumer/payment/feign/timeout") public String timeOUt () {return paymentFeignService.timeOUt ();}
4. Test result
Directly invoke the exposed service interface of the payment module 8001 and pass the test.
If the call is made through the order module, a timeout error is reported.
1.3.3. Time-out configuration
Add the following code to the YML file of the order module
Ribbon: ReadTimeout: 8000 ConnectTimeout: 8000
1. Test result
The self-test passed.
1.4, log printing 1.4.1, what is it?
Feign provides log printing, and we can adjust the log level through configuration to understand the details of Http requests in Feign. Is to monitor and output the calls to the feign interface.
1.4.2, log level
NONE: by default, no logs are displayed
BASIC: only record request method, URL, response status code and execution time
HEADERS: in addition to the information defined in BASIC, there is also header information for requests and responses
FULL: in addition to the information defined in HEADERS, there is also the body and metadata of the request and response.
1.4.3. How to turn on log printing
1. Write a log configuration class
Import feign.Logger;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class FeignConfig {@ Bean Logger.Level feignLoggerLevel () {return Logger.Level.FULL;}}
two。 Make relevant configuration in the YML file
Server: port: 80eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eurekaribbon: ReadTimeout: 8000 ConnectTimeout: 8000logging: level: com.atguigu.springcloud.service.PaymentFeignService: debug
3. Test result
4. Packet structure diagram
This is the end of the content of "how to use SpringCloud's OpenFeign to make service calls". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.