通过OpenFeign实现服务之间的接口调用

一、引入相关依赖

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

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

二、创建消费接口

@FeignClient(name="user-service",path = "/user")
public interface UserFeignService {

    @PostMapping("/add")
    String add();
}

name指定的是服务名称,path是请求的前缀,接口中的方法是指定服务方的请求方法

@RestController
@RequestMapping("chat")
public class ChatController {

    @Autowired
    private UserFeignService userFeignService;

    @GetMapping
    public void get(){
        System.out.println("进入聊天模块");
        System.out.println(userFeignService.add());
    }
}

当用户访问http://localhost:8011/chat时,会

三、在启动类中,添加@EnableFeignClients注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatApplication.class);
    }

}

当用户访问localhost:8011/chat方法时,先进入get()方法,然后执行add()调用user-service中的add()

posted @ 2025-09-16 19:42  派大星在干嘛  阅读(5)  评论(0)    收藏  举报