1、Ribbon+RestTemplate
1.1 Ribbon
Ribbon主要功能是提供客户端软件负载均衡算法和服务调用,属于进程内LB(负载均衡+restTemplate调用)。 负载均衡(LB)分为集中式和进程内,就是将用户请求平均分摊到多个服务器,从而达到系统高可用。
- 依赖:spring-cloud-starter-netflix-eureka-client集成引入了ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
例子:
1.2 RestTemplate
@Configuration
public class ApplicationConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
(1)常见方法
- getForObject/getForEntity
- postForObject/postForEntity
- GET请求方法
- POST请求方法
public class PaymentController {
public static final String payment_URL ="http://PAYMENT";
private final RestTemplate restTemplate ;
@GetMapping("/get/save")
public Result<Payment> saveEntity(Payment payment) {
return restTemplate.postForObject(payment_URL+"/payment/save",payment,Result.class);
}
@GetMapping("/{id}")
public Result getEntity(@PathVariable("id") Integer id) {
return restTemplate.getForObject(payment_URL+"/payment/"+id,Result.class);
}
@GetMapping("/entity/{id}")
public Result getForEntity(@PathVariable("id") Integer id) {
ResponseEntity<Result> resultResponseEntity = restTemplate.getForEntity(payment_URL+"/payment/"+id,Result.class);
if(resultResponseEntity.getStatusCode().is2xxSuccessful()){
return resultResponseEntity.getBody();
} else {
return new Result(404,"失败","");
}
}
}
1.3 Ribbon默认负载规则(IRule)
1.3.1 使用 Ribbon组件IRule有7种负载均衡规则实现,默认使用的是轮询; 如果要更改默认规则,自定义配置类不能放在@ComponentScan所扫描的当前包以及子包下面(主启动类扫描范围内),否则就会被所有Ribbion客户端共享,无法实现定制化。
配置类:MySelfRule.java
@Configuration
public class MySelfRule {
@Bean
public IRule iRule(){
return new RandomRule();
}
}
主启动类:添加扫描注解,value为注册的服务名,configuration为配置类名.class
@SpringBootApplication(scanBasePackages = "com.consumer")
@EnableEurekaClient
@RibbonClient(value = "PAYMENT",configuration = MySelfRule.class)
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
1.3.2 原理
- 轮询原理:
rest请求次数%服务器集群数 = 调用服务器下标(重启服务请求次数从1开始计算) 1%2 = 1 ,调用 list.get(1); 2%2 = 0 ,调用 list.get(0);
2、OpenFeign
服务接口调用。 (1)基本概念
- Feign是一个声明式的WebService客户端,使用方法是定义一个服务接口然后添加注解。
- Feign是对微服务客户端的进一步封装,Feign集成了ribbion。
- OpenFeign在OpenFeign的基础上支持springmvc注解,并通过代理的方式产生实现类,实现类中做负载均衡并调用服务。
(2)OpenFeign的使用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- application.yml 不注册进注册中心:register-with-eureka: false
server:
port: 8085
eureka:
client:
register-with-eureka: false
fetchRegistry: true
service-url:
defaultZone: http://eureka7001:7001/eureka,http://eureka7002:7002/eureka
spring:
application:
name : consumer8085
datasource:
url: jdbc:mysql://localhost:3306/springboot-mybatisplus?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name=com: mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config :
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
mapper-locations: classpath:mapper/*.xml
- 主启动类:@EnableFeignClients 激活
@SpringBootApplication(scanBasePackages = "com.payment")
@EnableFeignClients
public class Payment7Application {
public static void main(String[] args) {
SpringApplication.run(Payment7Application.class, args);
}
}
- 业务实现
PaymentFeignService.java
——@FeignClient(value = “PAYMENT”) ——@Component
@FeignClient(value = "PAYMENT")
@Component
public interface PaymentFeignService {
@GetMapping("/payment/{id}")
public Result<Payment> getEntity(@PathVariable("id") Integer id);
}
PaymentController .java
采坑7:@Resource注解注入
@RestController
@RequestMapping("/consumer4")
public class PaymentController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/payment/{id}")
public Result getById (@PathVariable("id") Integer id){
return paymentFeignService.getEntity(id);
}
}
访问:http://localhost:8085/consumer4/payment/1
(3)其他操作
- 超时控制:默认连接时间超过1秒返回超时异常,可以通过application.yml设置超时时间。
ribbon:
ReadTimeOut: 5000
ConnectT888imeout: 5000
- 日志增强
提供5中日志等级 ——配置类
@Configuration
public class FenConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
——配置开启
logging:
level:
com.payment.FeignService: debug
|