一、说明二、代码实现
一、说明这里先介绍Eureka client、Hystrix、ribbon等组件架构关系,后续继续完善他们的功能原理。
需要的jar包
org.springframework.cloud spring-cloud-starterorg.springframework.cloud spring-cloud-starter-netflix-eureka-clientorg.springframework.cloud spring-cloud-starter-netflix-eureka-server2.1.0.RELEASE org.springframework.cloud spring-cloud-starter-netflix-ribbonorg.springframework.boot spring-boot-starter-actuatororg.springframework.cloud spring-cloud-starter-netflix-hystrix
加上注解
@EnableDiscoveryClient //注解注册到服务中心 @EnableEurekaClient @EnableHystrix
Ribbon方式调用
@Configuration public class RestTemplateConfiguration { @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
服务消费者EurekaClient1—Ribbon+hystrix的方式
@Service public class RibbonPersonService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "personByIdHytrix") public String getPersonById(Integer id){ // http://localhost:7081/otherPerson/getPersonById.do?id=1 String result = restTemplate.getForObject( "http://eurekaClient2/getPersonById.do?id="+id,String.class); return result; } //熔断的功能 public String personByIdHytrix(Integer id){ return "personById Hytrix"; } }
服务提供者EurekaClient2–controller层的接口【只要子类实现即可】
public interface OtherPersonApi { @RequestMapping(value = "/getPersonById.do",method = RequestMethod.GET) String getPersonById(@RequestParam(value = "id") Integer id); @RequestMapping(value = "/insertPerson.do",method = RequestMethod.GET) PersonPo insertPerson(@RequestParam(value = "userId") Integer userId,@RequestBody PersonPo person); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)