1.首先
创建 Spring Boot 项目
使用 Spring Initializr 来创建基础的 Spring Boot 项目。选择如下选项:
- Project: Maven/Gradle
- Language: Java
- Spring Boot: 最新稳定版
- Dependencies: Web, JPA, MySQL, Actuator, Config Client, Eureka Discovery Client 等
示例代码:Service A
@SpringBootApplication
@EnableEurekaClient
public class ServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
}
@RestController
@RequestMapping("/api")
public class ServiceAController {
@GetMapping("/greeting")
public ResponseEntity<String> getGreeting() {
return ResponseEntity.ok("Hello from Service A");
}
}
2. 服务注册与发现
Eureka 服务注册中心
-
创建 Eureka Server:
-
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
-
配置 Eureka Server (
application.yml
):server: port: 8761 eureka: client: register-with-eureka: false fetch-registry: false
-
在微服务中配置 Eureka Client (
application.yml
):spring: application: name: service-a cloud: discovery: client: simple: registration: enabled: true eureka: client: service-url: defaultZone: http://localhost:8761/eureka/
3. 配置管理
使用 Spring Cloud Config 进行集中配置管理。
配置服务
-
创建 Config Server:
@SpringBootApplication @EnableConfigServer public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
-
配置 Config Server (
application.yml
):server: port: 8888 spring: cloud: config: server: git: uri: https://github.com/your-repo/config-repo searchPaths: '{application}'
-
配置客户端 (
application.yml
):spring: application: name: service-a cloud: config: uri: http://localhost:8888
4. 服务间通信
使用 RestTemplate
或 Feign Client
进行服务间调用。
示例:使用 Feign Client
-
添加依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
启用 Feign Client:
@SpringBootApplication @EnableFeignClients public class ServiceBApplication { public static void main(String[] args) { SpringApplication.run(ServiceBApplication.class, args); } }
-
定义 Feign Client 接口:
@FeignClient(name = "service-a") public interface ServiceAClient { @GetMapping("/api/greeting") String getGreeting(); }
-
在 Service B 中使用 Feign Client:
@RestController @RequestMapping("/api") public class ServiceBController { @Autowired private ServiceAClient serviceAClient; @GetMapping("/call-service-a") public ResponseEntity<String> callServiceA() { return ResponseEntity.ok(serviceAClient.getGreeting()); } }
5. 自动化部署与 CI/CD
- Docker 化服务: 使用 Dockerfile 容器化每个微服务。
- CI/CD 工具: 使用 Jenkins、GitHub Actions、GitLab CI 等实现自动化构建和部署。
6. 测试
- 单元测试: 使用 JUnit 和 Mockito 进行单元测试。
- 集成测试: 使用 Spring Boot Test 进行集成测试。
总结
通过以上步骤,你可以使用 Java 和 Spring Boot 构建一个基础的微服务架构。