Spring Boot 与 Spring Cloud 整合指南

Spring Boot 和 Spring Cloud 的整合可以快速构建分布式系统。以下为关键整合步骤和配置示例。


添加 Spring Cloud 依赖

pom.xml 中引入 Spring Cloud 的依赖管理,并选择对应的版本(如 Hoxton.SR12):

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR12</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


服务注册与发现(Eureka)

使用 Eureka 实现服务注册与发现:

  1. Eureka Server 配置
    创建服务注册中心:
@SpringBootApplication
@EnableEurekaServer
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. Eureka Client 配置
    服务提供者或消费者注册到 Eureka:
@SpringBootApplication
@EnableEurekaClient
public class ServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}

配置文件 application.yml

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/


声明式 REST 客户端(Feign)

通过 Feign 简化服务间 HTTP 调用:

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

  1. 启用 Feign 并定义接口:
@SpringBootApplication
@EnableFeignClients
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

@FeignClient(name = "service-provider")
public interface UserServiceClient {
    @GetMapping("/users/{id}")
    User getUser(@PathVariable Long id);
}


负载均衡(Ribbon)

Spring Cloud 默认集成 Ribbon,通过 @LoadBalanced 注解实现负载均衡:

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}

调用服务时直接使用服务名:

String url = "http://service-provider/users/1";
User user = restTemplate.getForObject(url, User.class);


断路器(Hystrix)

使用 Hystrix 实现服务熔断:

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

  1. 启用 Hystrix 并定义降级逻辑:
@SpringBootApplication
@EnableHystrix
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

@Service
public class UserService {
    @HystrixCommand(fallbackMethod = "getUserFallback")
    public User getUser(Long id) {
        // 远程调用逻辑
    }

    public User getUserFallback(Long id) {
        return new User("fallback-user");
    }
}


分布式配置中心(Config Server)

集中管理配置文件:

  1. Config Server 配置
    创建配置中心服务端:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

配置文件 application.yml

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo

  1. Config Client 配置
    客户端从配置中心读取配置:
spring:
  cloud:
    config:
      uri: http://localhost:8888
      name: service-name
      profile: dev


API 网关(Zuul 或 Gateway)

使用 Spring Cloud Gateway 路由请求:

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

  1. 配置路由规则:
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://service-provider
          predicates:
            - Path=/api/users/**


分布式链路追踪(Sleuth + Zipkin)

集成 Sleuth 和 Zipkin 追踪请求链路:

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-sleuth-zipkin</artifactId>
</dependency>

  1. 配置 Zipkin 服务器地址:
spring:
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
      probability: 1.0


通过以上模块的整合,可以快速构建一个功能完整的微服务系统。根据实际需求选择组件,并注意版本兼容性。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐