Spring Boot微服务入门教程介绍了Spring Boot框架的基本概念和优势,包括快速启动、自动配置和嵌入式Web服务器等功能。通过详细阐述环境搭建、创建第一个Spring Boot项目以及微服务之间的通信方式等内容,帮助开发者快速上手Spring Boot微服务开发。
Spring Boot简介Spring Boot是一个基于Spring框架的开源微服务框架,旨在简化Spring应用的初始搭建及开发过程。通过“约定优于配置”的理念,Spring Boot自动配置Spring应用,减少了配置文件的编写,让开发者能够快速地开发出独立的、生产级别的应用。
@EnableAutoConfiguration
注解,Spring Boot能够自动配置常见的开发场景。spring-boot-starter
依赖,提供了丰富的预定义依赖集合,如spring-boot-starter-web
、spring-boot-starter-data-jpa
等,帮助快速集成各种功能。spring-boot-maven-plugin
和spring-boot-gradle-plugin
,支持在Maven和Gradle构建工具中直接运行和打包应用。spring-boot-starter-actuator
,可以启用监控、健康检查、指标收集等功能。Spring Boot项目基于Java开发,因此首先需要安装Java环境。
wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/11.0.2+9/jdk-11.0.2_linux-x64_bin.tar.gz
tar -xzf jdk-11.0.2_linux-x64_bin.tar.gz
~/.bashrc
,添加以下内容:
export JAVA_HOME=/path/to/jdk export PATH=$JAVA_HOME/bin:$PATH
java -version
wget http://www.apache.org/dist/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz tar -xzf apache-maven-3.6.3-bin.tar.gz
wget https://services.gradle.org/distributions/gradle-6.8.3-bin.zip unzip gradle-6.8.3-bin.zip
PATH
环境变量中。
export PATH=$PATH:/path/to/apache-maven-3.6.3/bin export PATH=$PATH:/path/to/gradle-6.8.3/bin
mvn --version gradle -v
推荐使用IntelliJ IDEA或Eclipse来开发Spring Boot项目。
IntelliJ IDEA:
web
、data-jpa
等。Generate
按钮下载项目压缩包。手动创建一个简单的Spring Boot项目,包含主类和web控制器。
创建pom.xml
文件,配置Maven依赖。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
创建主类DemoApplication.java
:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
创建web控制器HelloController.java
:
package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String hello() { return "Hello, Spring Boot!"; } }
mvn spring-boot:run
依赖注入(Dependency Injection,DI)是一种设计模式,通过外部配置将组件的依赖关系从代码中解耦出来。Spring Boot通过注解和配置文件实现依赖注入。
创建一个服务类UserService.java
:
package com.example.demo; public class UserService { public String getUser() { return "User Service"; } }
创建一个控制器类UserController.java
,注入UserService
:
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public String getUser() { return userService.getUser(); } }
Spring Boot通过@EnableAutoConfiguration
注解自动配置应用,减少配置文件的编写。
创建一个配置类MyAutoConfiguration.java
:
package com.example.demo; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService() { return new MyService(); } }
创建一个服务类MyService.java
:
package com.example.demo; public class MyService { public String getMessage() { return "Hello from MyService!"; } }
在主类DemoApplication.java
中启用自动配置:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import(MyAutoConfiguration.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
Spring Boot启动器(Starters)是一系列预定义的依赖集合,简化了依赖管理和配置过程。
pom.xml
添加spring-boot-starter-data-jpa
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
创建配置类JpaConfig.java
:
package com.example.demo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; @Configuration public class JpaConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setPackagesToScan("com.example.demo"); return em; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } }
Spring Boot微服务通常包含多个模块,每个模块负责一个特定的服务功能。以下是创建微服务的步骤:
application.yml
或application.properties
配置服务端口、数据库连接等。创建主类UserServiceApplication.java
:
package com.example.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } }
配置文件application.yml
:
server: port: 8081 spring: application: name: user-service
创建服务类UserService.java
:
package com.example.user; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserService { @GetMapping("/user") public String getUser() { return "User Service"; } }
Spring Boot Actuator提供了一系列内置的监控和管理端点,帮助开发者了解服务的运行状态。
spring-boot-starter-actuator
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
management: endpoints: web: exposure: include: "*"
http://localhost:8081/actuator
,查看服务的健康状态、JVM性能指标等。使用Maven或Gradle命令启动微服务:
mvn spring-boot:run
将微服务打包成JAR文件,使用Docker容器化部署。
mvn clean package
FROM openjdk:11-jre-slim COPY target/user-service-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t user-service:v1 .
docker run -p 8081:8081 user-service:v1
RESTful API是一种基于HTTP协议的API设计风格,通过资源的URL、HTTP方法(GET、POST、PUT、DELETE等)来实现对资源的操作。
创建一个资源类UserResource.java
:
package com.example.user; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/users") public class UserResource { @GetMapping public String getUsers() { return "List of users"; } }
http://localhost:8081/users
,查看用户列表。Spring Boot通过@RestController
和@RequestMapping
注解快速实现RESTful服务。
创建一个资源类ProductResource.java
:
package com.example.product; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/products") public class ProductResource { @GetMapping public String getProducts() { return "List of products"; } }
UserService
和ProductService
),配置负载均衡(如Nginx或Spring Cloud Gateway)。微服务之间的通信方式主要有RESTful API、消息队列(如RabbitMQ、Kafka)和RPC(如gRPC)。
使用Spring Cloud OpenFeign实现服务调用
spring-cloud-starter-openfeign
依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
@FeignClient(name = "product-service") public interface ProductClient { @GetMapping("/products") String getProducts(); }
使用Feign客户端调用其他服务的API:
package com.example.user; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.example.product.ProductClient; @RestController public class UserController { @Autowired private ProductClient productClient; @GetMapping("/user/products") public String getProducts() { return productClient.getProducts(); } }
使用RabbitMQ实现消息队列通信
spring-boot-starter-amqp
依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
spring: rabbitmq: host: localhost port: 5672 username: guest password: guest
发送消息:
package com.example.user; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private RabbitTemplate rabbitTemplate; @GetMapping("/user/send") public void sendMessage() { rabbitTemplate.convertAndSend("queueName", "Hello, RabbitMQ!"); } }
接收消息:
package com.example.product; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class ProductReceiver { @RabbitListener(queues = "queueName") public void receiveMessage(String message) { System.out.println("Received message: " + message); } }
Spring Cloud Config提供了一个集中式的配置管理,支持多种存储后端(如Git、SVN)。
创建一个配置中心服务ConfigServerApplication.java
:
package com.example.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.ConfigServerApplication; import org.springframework.context.annotation.Configuration; @SpringBootApplication 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/my-repo search-paths: config-repo
创建一个配置客户端UserServiceApplication.java
:
package com.example.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.context.config.annotation.RefreshScope; @SpringBootApplication @EnableDiscoveryClient @RefreshScope public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } }
bootstrap.yml
:
spring: application: name: user-service cloud: config: uri: http://localhost:8888
Spring Cloud Hystrix提供了一套容错和熔断机制,可以保护微服务免受下游服务故障的影响。
spring-cloud-starter-netflix-hystrix
依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
使用@HystrixCommand
注解:
package com.example.user; import com.netflix.hystrix.HystrixCommand; import org.springframework.stereotype.Component; @Component public class HystrixCommandExample { @HystrixCommand(fallbackMethod = "fallback") public String execute() { // 调用外部服务 return "Success"; } public String fallback() { return "Fallback"; } }
Docker容器化微服务可以简化部署和管理流程,提高开发效率。
FROM openjdk:11-jre-slim COPY target/user-service-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"]
docker build -t user-service:v1 .
docker run -p 8081:8081 user-service:v1