feign如何使用?
生活随笔
收集整理的这篇文章主要介绍了
feign如何使用?
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
在客户端(User)引入依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>在启动类上面加上注解:@EnableFeignClients
然后编写一个service类加上@FeignClient()注解 参数就是你的微服务名字
@FeignClient("SERVER-POWER") public interface PowerServiceClient {@RequestMapping("/power.do")public Object power();}下面是调用代码:
import com.luban.service.OrderServiceClient; import com.luban.service.PowerServiceClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;@RestController public class UserController {private static final String URL="http://SERVER-POWER";@Autowiredprivate RestTemplate restTemplate;@AutowiredPowerServiceClient powerServiceClient;@RequestMapping("/power.do")public Object power(){return restTemplate.getForObject(URL+"/power.do",Object.class);}@RequestMapping("/feignPower.do")public Object feignPower(){return powerServiceClient.power();}}这里拿了RestTemplate做对比 可以看看2者区别
Feign集成了Ribbon
利用Ribbon维护了服务列表信息,并且融合了Ribbon的负载均衡配置,也就是说之前自定义的负载均衡也有效,这里需要你们自己跑一遍理解一下。而与Ribbon不同的是,通过feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用
总结
以上是生活随笔为你收集整理的feign如何使用?的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: feign 能干什么:
- 下一篇: hystrix是什么?