Spring Cloud微服务架构:从入门到实践

Spring Cloud为开发人员提供了快速构建分布式系统的工具,本文将详细介绍Spring Cloud的核心组件和最佳实践。

服务注册与发现

Eureka Server配置

1
2
3
4
5
6
7
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# application.yml
server:
  port: 8761

eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
  server:
    waitTimeInMsWhenSyncEmpty: 0

Eureka Client配置

1
2
3
4
5
6
7
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}
1
2
3
4
5
6
7
8
spring:
  application:
    name: user-service

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

服务调用

Feign声明式调用

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

@RestController
public class OrderController {
    
    @Autowired
    private UserClient userClient;
    
    @GetMapping("/orders/{orderId}/user")
    public User getUserByOrderId(@PathVariable Long orderId) {
        Order order = orderService.getOrder(orderId);
        return userClient.getUser(order.getUserId());
    }
}

负载均衡

Ribbon配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@Configuration
public class RibbonConfig {
    
    @Bean
    public IRule ribbonRule() {
        return new WeightedResponseTimeRule();
    }
}

@RibbonClient(name = "user-service", configuration = RibbonConfig.class)
public class ServiceConfiguration {
}

服务熔断

Hystrix配置

1
2
3
4
5
6
7
@EnableCircuitBreaker
@SpringBootApplication
public class ServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Service
public class UserService {
    
    @HystrixCommand(fallbackMethod = "getUserFallback",
        commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000")
        })
    public User getUser(Long id) {
        return userClient.getUser(id);
    }
    
    public User getUserFallback(Long id) {
        return new User("默认用户");
    }
}

配置中心

Config Server

1
2
3
4
5
6
7
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}
1
2
3
4
5
6
7
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/config-repo
          searchPaths: '{application}'

Config Client

1
2
3
4
5
spring:
  cloud:
    config:
      uri: http://localhost:8888
      label: master
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@RefreshScope
@RestController
public class ConfigController {
    
    @Value("${custom.property}")
    private String customProperty;
    
    @GetMapping("/property")
    public String getProperty() {
        return customProperty;
    }
}

服务网关

Spring Cloud Gateway

1
2
3
4
5
6
7
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
spring:
  cloud:
    gateway:
      routes:
        - id: user_service
          uri: lb://user-service
          predicates:
            - Path=/users/**
          filters:
            - StripPrefix=1
            - name: CircuitBreaker
              args:
                name: userCircuitBreaker
                fallbackUri: forward:/fallback

分布式链路追踪

Sleuth + Zipkin

1
2
3
4
5
6
7
8
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
1
2
3
4
5
6
spring:
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
      probability: 1.0

消息总线

Spring Cloud Bus

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@RefreshScope
@RestController
public class ConfigController {
    
    @Autowired
    private BusProperties busProperties;
    
    @PostMapping("/actuator/bus-refresh")
    public void refresh() {
        // 刷新配置
    }
}

安全配置

OAuth2集成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@EnableResourceServer
@SpringBootApplication
public class ResourceServerApplication {
    
    @Bean
    public ResourceServerConfigurer resourceServerConfigurer() {
        return new ResourceServerConfigurerAdapter() {
            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                    .authorizeRequests()
                    .antMatchers("/public/**").permitAll()
                    .anyRequest().authenticated();
            }
        };
    }
}

监控管理

Spring Boot Admin

1
2
3
4
5
6
7
@EnableAdminServer
@SpringBootApplication
public class AdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
spring:
  boot:
    admin:
      client:
        url: http://localhost:8080
management:
  endpoints:
    web:
      exposure:
        include: "*"

最佳实践

  1. 服务拆分原则

    • 单一职责
    • 服务粒度适中
    • 考虑业务边界
  2. 配置管理

    • 使用配置中心
    • 环境隔离
    • 敏感信息加密
  3. 高可用设计

    • 服务多实例
    • 熔断降级
    • 负载均衡

性能优化

  1. 服务调用优化
1
2
3
4
5
6
7
@Configuration
public class FeignConfig {
    @Bean
    public Retryer feignRetryer() {
        return new Retryer.Default(100, 1000, 4);
    }
}
  1. 缓存优化
1
2
3
4
@Cacheable(value = "users", key = "#id")
public User getUser(Long id) {
    return userClient.getUser(id);
}

总结

Spring Cloud提供了构建微服务架构的完整解决方案,通过合理使用其组件可以快速构建可靠的分布式系统。

参考资料

  • Spring Cloud官方文档
  • Spring Cloud微服务实战
  • Spring Cloud Alibaba实战指南
使用绝夜之城强力驱动