Feign can still be used like this, you know?

table of Contents

Preface

Generally, we use Feign to call the service interface registered by the registry, but in fact, we can also use Feign to request third-party URLs.


Request third party url

1. Import Feign dependencies

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

Because I added spring-cloud-dependencies, so there is no need to add the version number. If spring-cloud-dependencies is not added to the pom, then you need to specify the version number

2. Define FeginClient interface

First add the @EnableFeignClients annotation to the startup class so that the Feign interface can be scanned.
If the Feign interface is not in the package of the startup class, then basePackages needs to be specified.

例:@EnableFeignClients(basePackages = "com.xxx.yyy.client")

The following url is the path of my csdn

@FeignClient(url = "https://blog.csdn.net" ,name="test")
public interface FeignClientInterface {
    
    
    @RequestMapping(value = "/qq_36551991",method = RequestMethod.GET)
    public String getMyCsdn();
}

To request a third-party url, fill in the name and value of @FeignClient at will, because this is a required attribute of the @FeignClient annotation, write the attribute value freely, the most important thing to request a third-party url is to fill
in the url attribute of the FeignClient annotation, this url is Fill in the url prefix of our request, and then splice the complete url in the FeignClient method. Because my request returns a url, I use String to receive, and the input and output parameters are defined according to actual needs.

Extra: Both the name and url attributes support placeholders, examples are as follows

#在application.properties填写配置属性
feign.client.url=https://blog.csdn.net

//在FeignClient注解中使用占位符,${属性}
@FeignClient(url = "${feign.client.url}",value = "testFeign")

3. Test

Define a Controller to test

@RestController
public class FeignTest {
    
    

    @Resource
    private FeignClientInterface feignClientInterface;

    @PostMapping("testFeign")
    public String testController2(){
    
    
        String myCsdn = feignClientInterface.getMyCsdn();
        System.out.println(myCsdn);
        return myCsdn;
    }


}

Use postman request, return successfully
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36551991/article/details/112149882