OpenFeign 使用
1.服务提供者 略过
2.服务消费者
1.需要引入依赖:
spring-cloud-starter-netflix-eureka-client,
spring-cloud-starter-openfeign,
spring-boot-starter-web
- 配置文件
spring.application.name=business3
server.servlet.context-path=/business3
server.port=9004
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
- 启动类注意要加注解**@EnableEurekaClient和@EnableFeignClients**
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Client3Application {
private static final Logger LOG = LoggerFactory.getLogger(Client3Application.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Client3Application.class);
Environment env = app.run(args).getEnvironment();
LOG.info("启动成功!!");
LOG.info("Business3地址: \thttp://127.0.0.1:{}", env.getProperty("server.port"));
}
}
- 新建FeignConfig,OpenFeign接口
@Configuration
public class FeignConfig {
@Bean
public Retryer feignRetryer() {
return new Retryer.Default(100, SECONDS.toMillis(1), 5);
}
}
@FeignClient(value = "business2",configuration = FeignConfig.class)
public interface OpenFeign {
@GetMapping(value = "/business2/business2/hi")
String sayHiFrombusiness2(@RequestParam(value = "name") String name);
}
这里方法上面的GetMapping要特别注意和浏览器访问地址保持一致。
举例:访问地址:http://127.0.0.1:9003/business2/business2/hi?name=ee
GetMapping的value: /business2/business2/hi
类上面FeignClient注解的value是服务提供者注册到eureka的服务名。
- 调用
service用@Autowire注入,如果启动类不加@EnableFeignClients会报错的。controller注入service和之前一样。