feign怎么用在启动类
时间: 2023-05-30 10:06:48 浏览: 104
Feign可以用作远程服务调用的客户端,可以在启动类中通过注解的方式来配置Feign客户端。
首先需要在启动类上加上@EnableFeignClients注解,开启Feign客户端功能。然后再创建一个接口,使用@FeignClient注解来指定要调用的服务名,以及调用服务的路径和参数等信息。最后在启动类中通过@Autowired注解来注入Feign客户端接口,即可在业务逻辑代码中直接调用该接口来访问远程服务。
下面是一个简单的例子:
```java
@SpringBootApplication
@EnableFeignClients
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@FeignClient(name = "my-service", url = "http://localhost:8080")
public interface MyServiceClient {
@GetMapping("/my-service/hello")
String sayHello();
}
@RestController
public class MyController {
@Autowired
private MyServiceClient myServiceClient;
@GetMapping("/hello")
public String sayHello() {
return myServiceClient.sayHello();
}
}
```
在上面的例子中,@EnableFeignClients注解开启了Feign客户端功能,@FeignClient注解指定了要调用的服务名和服务路径。在MyController中,通过@Autowired注入了MyServiceClient接口,然后在sayHello方法中调用了该接口的sayHello方法来访问远程服务。