和ribbon一样feign也可以作微服务的负载均衡,使用feign来调用的api接口让api接口更像是本地的接口
/**
*
* 一个服务注册中心,eureka server,端口为8761 service-hi工程跑了两个实例,端口分别为8762,8763,分别向服务注册中心注册
* sercvice-ribbon端口为8764,向服务注册中心注册
* 当sercvice-ribbon通过restTemplate调用EURKA-CLIENT的hi接口时,
* 因为用ribbon进行了负载均衡,会轮流的调用EURKA-CLIENT:8762和8763 两个端口的hi接口;
*/
// feign 自带了hystrix ,只需要开启hystrix功能就可以了:feign.hystrix.enabled=true
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
/**
* 通过feign 获取eurka-client服务提供的api接口
*/
@FeignClient(value = "eurka-client",fallback = SchedualServiceHiHystric.class)
public interface ScheduleService {
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHi(@RequestParam(value = "name") String name);
}
@Component
public class SchedualServiceHiHystric implements ScheduleService {
@Override
public String sayHi(String name) {
return "sorry "+name;
}
}
@RestController
public class HelloControler {
// 编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。
@Autowired
ScheduleService schedualService;
@GetMapping(value = "/hi")
public String sayHi(@RequestParam String name) {
return schedualService.sayHi(name);
}
}