import cn.itbluebox.order.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“/order”)
public class OrderController {
@Autowired
private ProductFeignClient productFeignClient;
@RequestMapping(value = “/buy/{id}”, method = RequestMethod.GET)
public Product findById(@PathVariable Long id) {
//如何调用商品服务?
return productFeignClient.findById(id);
}
}
(5)运行测试
访问测试
http://localhost:9002/order/buy/1
Ribbon是一个基于 HTTP 和 TCP 客户端 的负载均衡的工具。
它可以 在客户端 配置RibbonServerList(服务端列表),使用 HttpClient 或 RestTemplate 模拟http请求,步骤相当繁琐。
Feign 是在 Ribbon的基础上进行了一次改进,是一个使用起来更加方便的 HTTP 客户端。采用接口的方式, 只需要创建一个接口,然后在上面添加注解即可 ,将需要调用的其他服务的方法定义成抽象方法即可, 不需要自己构建http请求。
然后就像是调用自身工程的方法调用,而感觉不到是调用远程方法,使得编写客户端变得非常容易
Feign中本身已经集成了Ribbon依赖和自动配置,因此我们不需要额外引入依赖,也不需要再注册RestTemplate 对象。
另外,我们可以像上节课中讲的那样去配置Ribbon,可以通过 ribbon.xx 来进行全局配置。
也可以通过 服务名.ribbon.xx 来对指定服务配置:
(1)修改OrderService的启动类设置OrderApplication
package cn.itbluebox.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EntityScan(“cn.itbluebox.order.entity”)
@EnableFeignClients
public class OrderApplication {
/*
使用Spring提供的 RestTemplate 发送http请求到商品服务
1、创建RestTemplate对象交给容器管理
2、在使用的时候,调用其方法完成操作(getXX,postXX)
@LoadBalanced : 是Ribbon提供的负载均衡的注解
*/
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class,args);
}
}
(2)启动第二个product_service
修改product_service的pom.xml
设置端口号为9011