springcloud常用注解介绍以及代码示例
时间: 2023-09-22 21:09:49 浏览: 185
springcloud代码示例,包括erueka,hystrix,ribbon的使用
1. @EnableDiscoveryClient
@EnableDiscoveryClient注解用于启用服务注册与发现,包含Eureka,Consul等服务发现组件。
示例:
```java
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. @FeignClient
@FeignClient注解用于定义Feign客户端接口。
示例:
```java
@FeignClient("service-provider")
public interface ProviderClient {
@GetMapping("/hello")
String hello();
}
```
3. @HystrixCommand
@HystrixCommand注解用于定义熔断器的fallback方法。
示例:
```java
@HystrixCommand(fallbackMethod = "fallback")
public String hello() {
return restTemplate.getForObject("http://service-provider/hello", String.class);
}
public String fallback() {
return "fallback";
}
```
4. @EnableHystrix
@EnableHystrix注解用于启用Hystrix熔断器。
示例:
```java
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
5. @EnableCircuitBreaker
@EnableCircuitBreaker注解是@EnableHystrix的别名,用于启用Hystrix熔断器。
示例:
```java
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
6. @RefreshScope
@RefreshScope注解用于实现配置动态刷新。
示例:
```java
@RestController
@RefreshScope
public class ConfigController {
@Value("${config}")
private String config;
@GetMapping("/config")
public String getConfig() {
return config;
}
}
```
7. @EnableConfigServer
@EnableConfigServer注解用于启用配置中心服务。
示例:
```java
@SpringBootApplication
@EnableConfigServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
8. @EnableZuulProxy
@EnableZuulProxy注解用于启用Zuul网关。
示例:
```java
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
9. @EnableEurekaClient
@EnableEurekaClient注解用于启用Eureka客户端。
示例:
```java
@SpringBootApplication
@EnableEurekaClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
阅读全文