OpenFeign实现负载均衡
OpenFeign
是一个声明式的web服务客户端
,让编写web服务客户端变的非常容易,只需要创建一个接口并在接口上添加注解即可。相较于Ribbon实现负载均衡,需要硬编码请求URL,不利于程序的可读性。
OpenFeign是Spring Cloud在Feign的基础上支持了Spring MVC的注解,列如@RequestMapping
等,OpenFeign的@FeignClient
可以解析SpringMVC的@RequestMapping
注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。
步骤一:加入OpenFeign依赖
<!--open feign 帮助服务消费-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
步骤二 在服务消费端创建服务调用接口
创建时,可以根据服务提供的Controller类进行编写
- 服务提供者Controller
@RestController
public class SystemsController {
@Autowired
private AppSystemService appSystemService;
private Logger logger= LoggerFactory.getLogger(SystemsController.class);
@Value("${server.port}")
private String port;
@GetMapping(value = "/systems/getSystemById/{systemsId}")
public ReturnMessageModel<AppSystemsInfo> getSystemById(@PathVariable("systemsId") String systemsId)
{
logger.info("this.port"+port);
return appSystemService.getSystemById(systemsId);
}
@PostMapping("/insertSystemsInfo")
public ReturnMessageModel insertSystemsInfo(AppSystemsInfo systemsInfo){
logger.info("this.port"+port);
return appSystemService.addSystemsInfo(systemsInfo);
}
}
- 服务消费者编写的接口 【@FeignClient的注解的应用】
//FeignClient name:服务注册的名称,fallback 服务调用异常时的处理Interceptor
//configuration Client的配置类【多用于服务调用时的局部配置,指定某一个特殊服务时生效】
@Resource
@FeignClient(name="userprivilege",fallback = FallBack_PrivilegeService.class /**,configuration = FeignConfig.class*/)
public interface PrivilegeService {
/**
* 根据系统id获得配置系统信息
* @param systemsId
* @return
*/
@GetMapping(value = "/systems/getSystemById/{systemsId}")
ReturnMessageModel<AppSystemsInfo> getSystemById(@PathVariable("systemsId") String systemsId);
/**
* 插入配置系统信息
* @param systemsInfo
* @return
*/
@PostMapping("/insertSystemsInfo")
ReturnMessageModel insertSystemsInfo(AppSystemsInfo systemsInfo);
}
步骤三 激活FeignClien
//EnableFeignClients注解开启Feign客户端服务消费功能
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
@RibbonClients({
@RibbonClient(name = "userprivilege",configuration = MyRuleConfiguration.class)
})
public class BaseConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(BaseConsumerApplication.class,args);
}
}
步骤四. 服务消费端Controller
@RestController()
public class AppController {
@Autowired
private PrivilegeService privilegeService;
/**
* 根据openfeign组件实现负载均衡,声明式服务调用,解决了restTemplate硬编码请求的问题
* 根据系统id获得系统配置信息
* @param systemsId
* @return
*/
@GetMapping("consumer/getSystemById/{systemsId}")
public ReturnMessageModel<AppSystemsInfo> getSystemById1(@PathVariable String systemsId){
return privilegeService.getSystemById(systemsId);
}
}