新建一个springboot项目,引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.3</version>
</dependency>
<!--loadbalancer包必须引入,因为openfeign底层集成了ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>3.1.3</version>
</dependency>
启动类加上注解
@EnableFeignClients(basePackages = {"com.example"}) @ImportAutoConfiguration({FeignAutoConfiguration.class})
编写代码
package com.example.demospringboot3.openfeign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "baiduFeignClient" , url = "http://127.0.0.1:8888")
public interface BaiduFeignClient {
@RequestMapping("/test2")
void getT1();
}
package com.example.demospringboot3.openfeign;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FeignController {
@Resource
private BaiduFeignClient baiduFeignClient;
@GetMapping("/feign")
public void feign() {
System.out.println("2222222222");
baiduFeignClient.getT1();
System.out.println("2222222222");
}
}