Ribbon的使用
一、加入依赖
spring-cloud-starter-netflix-ribbon (spring-cloud-starter-ribbon)
二、消费者工程,负载均衡初始化RestTemplate
@SpringBootApplication(scanBasePackage="com.springboot.product")
public class ChapterProductApplication{
@LoadBalanced //多节点负载均衡
@Bean(name="restTemplate")
public RestTemplate initRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args){
SpringApplication.run(ChapterProductApplication.class,args);
}
}
三、Controller进行微服务调用
@RestController
@RequestMapping("/product")
public class ProductController{
@Autowired
private RestTemplate restTemplate = null;
@GetMapping("/ribbon")
public UserPo testRibbon(){
UserPo user = null;
//循环10次进行调用
for(int i = 0;i < 10;i++){
//USER表示服务器及其端口(Eureka服务器中可以看到各个节点)
user = restTemplate.getForObject("http://USER/user/" + (i+1),UserPo.class);
}
return user;
}
}
四、浏览器输入
http://localhost:9001/product/ribbon
结果可以看到两个被调用的微服务各有5条日志
Feign的使用
声明式调用组件
一、引入依赖
spring-cloud-starter-openfeign (spring-cloud-starter-feign)
二、启用Feign
@EnableFeignClients
@SpringBootApplication(scanBasePackages="com.springboot.chapter.product")
@EnableFeignClients(scanBasePackages="com.springboot.chapter.product")
public class ChapterProductApplication{
public static void main(String[] args){
SpringApplication.run(ChapterProductApplication.class,args);
}
}
三、定义Feign接口
@FeignClient("user") //指定要调用的服务(服务注册中心的注册服务)
@Repository //为了避免消费端报错
public interface UserService{
/**
将user服务模块中的方法复制过来
*/
@GetMapping("/user/{id}")
public UserPo getUser(@PathVariable("id") Long id);//远程调用的参数必须指定@PathVariable的注解参数名id
}
【如果是独立于调用方的一个模块,需要将坐标引入到调用方的依赖中】
四、使用Feign调度用户的REST端点
在服务消费端调用方的模块中,Service层进行注入Feign接口
@Autowired
private UserService userService = null;
@GetMapping("/feign")
public UserPo testFeign(){
UserPo user = null;
//循环10次
for(int i = 0;i<10;i++){
Long id = (long)(i+1);
user = userService.getUser(id);
}
return user;
}
OpenFeign的使用
消费者服务调用接口+@FeignClient
一、依赖
spring-cloud-starter-openfeign
spring-cloud-starter-netflix-eureka-client
二、配置类
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http:eureka7002.com:7002/eureka/
# 设置feign客户端所用的事件
ribbon:
ReadTimeout: 5000
# 建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
# 日志增强配置
logging:
level:
# 以什么级别监控哪个接口
com.michael.springcloud.service.PaymentFeignService: debug
三、启动类
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80{
public static void main(String[] args){
SpringApplication.run(OrderFeignMain80.class,args);
}
}
四、业务接口
@Component
@FeignClient(value = "指定注册在Eureka中微服务名称")
public interface PayMentFeignService{//某个微服务下的某个地址
@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
五、控制类Controller
@RestController
@slf4j
public class OrderFeignController{
@Resource
private PaymentFeignService paymentFeignService; //注入接口
}
附加:日志增强配置
@Configuration
public class FeignConfig{
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}