作者:Eyebros | 来源:互联网 | 2023-05-17 17:43
1、POM配置和普通SpringBoot工程相比,添加了EurekaClient、Feign、Hystrix依赖和SpringCloud依赖管理<dependencies>&
1、POM配置
和普通Spring Boot工程相比,添加了Eureka Client、Feign、Hystrix依赖和Spring Cloud依赖管理
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-eurekaartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-feignartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-hystrixartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
dependencies><dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud
groupId> <artifactId>spring-cloud-dependencies
artifactId> <version>Dalston.SR1
version> <type>pom
type> <scope>import
scope> dependency> dependencies>dependencyManagement>
02、使能
@SpringBootApplication
@EnableFeignClients //声明式服务消费
@EnableCircuitBreaker //断路器
@EnableEurekaClient //Eureka客户端public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
03、src/main/resources工程配置文件 application.yml
server:
port: 3010
spring:
application:
name: feign-hello-service-consumer
eureka:
client:
serviceUrl:
defaultZone: http://discovery:1000/eureka/
feign:
hystrix:
enabled: true #在新版本Feign中,hystrix默认关闭,必须手动打开
04、声明式服务消费
@FeignClient(name = "hello-service-provider", fallback = HelloFallback.class)
public interface HelloFeignService {
@RequestMapping("/hello")
public String hello();
}
@Component
class HelloFallback implements HelloFeignService {
@Override
public String hello() {
return "Error";
}
}
05、Controller
@RestController
public class FeignController {
@Autowired
private HelloFeignService helloService;
@GetMapping("feign")
public String hello() {
return this.helloService.hello(); }
}