引言

Spring Cloud是微服务开发的全家桶。本文介绍其核心组件和应用。

一、服务注册与发现(Eureka)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Eureka Server
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

// application.yml
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Eureka Client
@EnableEurekaClient
@SpringBootApplication
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}

// application.yml
spring:
application:
name: user-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/

二、服务调用(Feign)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/users/{id}")
User getUser(@PathVariable Long id);
}

@RestController
public class OrderController {
@Autowired
private UserClient userClient;

@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {
User user = userClient.getUser(id);
// 业务逻辑
return order;
}
}

三、API网关(Gateway)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

// application.yml
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**

四、配置中心(Config)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Config Server
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {}

// Config Client
@SpringBootApplication
public class ServiceApplication {
@Value("${my.config}")
private String config;
}

// bootstrap.yml
spring:
cloud:
config:
uri: http://localhost:8888
name: application
profile: dev

五、熔断器(Resilience4j)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Service
public class UserService {
@Autowired
private UserClient userClient;

@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public User getUser(Long id) {
return userClient.getUser(id);
}

public User fallback(Long id, Exception e) {
return new User(id, "Default User");
}
}

// application.yml
resilience4j:
circuitbreaker:
instances:
userService:
failure-rate-threshold: 50
wait-duration-in-open-state: 10s

总结

Spring Cloud核心组件:

  1. Eureka:服务注册与发现
  2. Feign:声明式HTTP客户端
  3. Gateway:API网关
  4. Config:配置中心
  5. Resilience4j:熔断降级

参考资料