1.基于Feign实现远程调用时的负载均衡
1.1初步配置
1.添加依赖(服务调用方)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.启动类添加@EnableFeignClients,表明要通过feign进行远程调用,会自动扫描带有@feign注解的接口,为其创建实现类,并交给sping管理
3.创建一个接口用来实现远程调用的声明:
@FeignClient(name="sca-provider")//sca-provider为服务提供者名称
public interface RemoteProviderService{
@GetMapping("/provider/echo/{string}")//前提是远端需要有这个服务
public String echoMessage(@PathVariable("string") String string);
}
4.基于feign远程调用,前需要注入接口的实现类,第三步中系统已经自动交给容器管理
@RestController
@RequestMapping("/consumer/ ")
public class FeignConsumerController {
@Autowired
private RemoteProviderService remoteProviderService;
/**基于feign方式的服务调用*/
@GetMapping("/echo/{msg}")
public String doFeignEcho(@PathVariable String msg){
//基于feign方式进行远端服务调用(前提是服务必须存在)
return remoteProviderService.echoMessage(msg);
}
}
1.2 进阶
1.2.1 contextId的引入
问题描述
远程服务提供的服务调用接口不止一个,当有多个接口的时候,我们要注入
@Autowired
private RemoteProviderService remoteProviderService;
就会提示
The bean 'optimization-user.FeignClientSpecification', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
此时我们需要为远程调用服务接口指定一个contextId,作为远程调用服务的唯一标识(这个标识是Bean对象的名字)即可,例如:
@FeignClient(name="sca-provider",contextId="remoteProviderService")//sca-provider为服务提供者名称
interface RemoteProviderService{
@GetMapping("/provider/echo/{string}")//前提是远端需要有这个服务
public String echoMessage(@PathVariable("string") String string);
}
1.2.2 FallbackFactory:服务调用端提供调用出错的回应
问题描述
当服务调用方调用服务提供方的时候,若服务提供方请求被拒绝或者请求超时,会在请求页面展示405界面,这对用户不友好,所以我们希望通过截取被拒绝的请求,将调用方制定好的反馈给用户
使用步骤
1.定义一个类,实现FallbackFactory,并把这个类交给spring管理
package com.cy.service.factory;
/**
* 基于此对象处理RemoteProviderService接口调用时出现的服务中断,超时等问题
*/
@Component
public class ProviderFallbackFactory implements FallbackFactory<RemoteProviderService> {
/**
* 此方法会在RemoteProviderService接口服务调用时,出现了异常后执行.
* @param throwable 用于接收异常
*/
@Override
public RemoteProviderService create(Throwable throwable) {
return (msg)->{
return "服务维护中,稍等片刻再访问";
};
}
}
2.在Feign访问接口中应用FallbackFactory对象
@FeignClient(name = "sca-provider", contextId = "remoteProviderService",
fallbackFactory = ProviderFallbackFactory.class)//sca-provider为nacos中的服务名
public interface RemoteProviderService {
@GetMapping("/provider/echo/{msg}")
public String echoMsg(@PathVariable String msg);
}
3.在配置文件application.yml中添加如下配置,启动feign方式调用时的服务中断处理机制.
feign:
hystrix:
enabled: true #默认值为false