服务提供者,是位于其余项目里面的。
服务提供者提供的方法,在Controller层里面,有可访问的Url。html
@Controller @RequestMapping("/order") public class OrderDetailController { @ResponseBody @RequestMapping(value="/detail/cdkey",method=RequestMethod.POST) public OrderDetail getOrderDetailByCdkey(@RequestParam("cdkey") String cdkey){ //其余逻辑忽略 } }
@FeignClient里面的value为服务提供者的服务名,fallback为服务熔断的class。
@RequestMapping的value属性为服务提供者的Url。json
@FeignClient(value = "base",fallback = OrderDetailHystrix.class) public interface OrderDetailService { @RequestMapping(value="order/detail/cdkey",method=RequestMethod.POST) JSONObject getOrderDetailByCdkey(@RequestParam("cdkey") String cdkey); }
除了使用如上的@RequestParam,还能够使用@RequestBody传递对象,好比app
@RequestMapping(value="order/detail/cdkey",method=RequestMethod.POST) JSONObject getOrderDetailByCdkey(@RequestBody User user);
若是须要使用占位符,也能够用@PathVariable,示例以下:ide
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET) Result get(@PathVariable("id") Integer id);
注意,最好让方法参数注解和服务提供者的方法参数注解保持一致。微服务
出现异常,能够经过熔断保护服务。
熔断器要实现Feign接口。还要加上注解@Component。code
@Component public class OrderDetailHystrix implements OrderDetailService { @Override public JSONObject getOrderDetailByCdkey(String cdkey) { JSONObject resultJson = new JSONObject(); resultJson.put("errcode",AUTH_ORDER_SERVICE_ERROR.getCode() ); resultJson.put("description", AUTH_ORDER_SERVICE_ERROR.getMsg() ); return resultJson; } }
能够在其余类(Service或Controller均可以)中注入已经声明的Feign接口,并调用其中的方法。
注入方式以下所示:htm
@Autowired private OrderDetailService OrderDetailService;
使用服务中的方法:对象
//调用订单详情服务,获取订单日期 JSONObject jsonObject=orcmOrderDetailService.getOrderDetailByCdkey(cdkey);
若是在使用Feign进行服务消费时出错,能够参考如下内容进行排错:
微服务SpringCloud没法进行服务消费
Spring Cloud Feign踩坑记录(二)blog