springcloud的10个常用注解作用及代码示例
时间: 2023-08-31 18:09:20 浏览: 96
1. @EnableDiscoveryClient:启用服务发现功能,让服务能够注册到注册中心。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
2. @EnableFeignClients:启用Feign客户端,简化服务调用。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
3. @FeignClient:定义Feign客户端,指定调用的服务名称。
示例:
```
@FeignClient("user-service")
public interface UserServiceClient {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
}
```
4. @EnableCircuitBreaker:启用熔断器功能,保护服务调用。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
5. @HystrixCommand:定义熔断器方法,指定熔断策略。
示例:
```
@Service
public class UserService {
@Autowired
private UserServiceClient userServiceClient;
@HystrixCommand(fallbackMethod = "getUserByIdFallback")
public User getUserById(Long id) {
return userServiceClient.getUserById(id);
}
private User getUserByIdFallback(Long id) {
return new User(id, "default", "default");
}
}
```
6. @EnableHystrixDashboard:启用熔断器仪表盘,监控服务调用。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
7. @EnableZuulProxy:启用Zuul网关,实现路由和过滤等功能。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
8. @RequestMapping:定义请求映射,指定请求路径和请求方法。
示例:
```
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") Long id) {
return userService.getUserById(id);
}
}
```
9. @EnableConfigServer:启用配置中心,实现动态配置管理。
示例:
```
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
10. @RefreshScope:定义可刷新的bean,实现动态更新配置。
示例:
```
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
@Value("${config.name}")
private String configName;
@GetMapping("/name")
public String getConfigName() {
return configName;
}
}
```
阅读全文