Java之 Spring Cloud 微服务搭建 Feign组件(第二个阶段

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

在这里插入图片描述

3、 Feign和Ribbon的联系


Ribbon是一个基于 HTTP 和 TCP 客户端 的负载均衡的工具。

它可以 在客户端 配置RibbonServerList(服务端列表),使用 HttpClient 或 RestTemplate 模拟http请求,步骤相当繁琐。

Feign 是在 Ribbon的基础上进行了一次改进,是一个使用起来更加方便的 HTTP 客户端。采用接口的方式, 只需要创建一个接口,然后在上面添加注解即可 ,将需要调用的其他服务的方法定义成抽象方法即可, 不需要自己构建http请求。

然后就像是调用自身工程的方法调用,而感觉不到是调用远程方法,使得编写客户端变得非常容易

4、负载均衡


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值