本文详细介绍了如何使用SpringCloud Alibaba进行微服务开发,涵盖了Nacos服务注册与发现、Sentinel流量控制、Seata分布式事务管理等核心组件的使用方法。通过详细的步骤和示例代码,帮助开发者快速构建和管理大规模微服务应用。文章还提供了丰富的SpringCloud Alibaba资料,包括官方文档、社区资源和视频教程,供读者深入学习。SpringCloud Alibaba资料简介了各个组件的配置和使用,方便开发者快速上手。
SpringCloud Alibaba简介与环境搭建SpringCloud Alibaba是阿里巴巴开源的一个基于SpringCloud的微服务解决方案。它提供了对Nacos、Sentinel、Seata等组件的支持,可以为微服务架构提供服务注册与发现、配置管理、流量控制、分布式事务等功能,使得构建大规模微服务应用更加容易。
为了快速搭建SpringCloud Alibaba开发环境,你需要准备以下工具和环境:
sh bin/startup.sh -m standalone
启动Nacos服务,默认端口为8848。Nacos启动后可以在浏览器中访问http://localhost:8848/nacos
查看Nacos的管理界面。Spring Initializer
创建一个新的Spring Boot项目。<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Cloud Alibaba Nacos Discovery --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
application.yml
文件,添加Nacos服务地址:spring: application: name: demo-app cloud: nacos: discovery: server-addr: 127.0.0.1:8848
@EnableDiscoveryClient
注解,启用服务注册与发现功能:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
java -jar sentinel-dashboard-1.8.2.jar
启动Sentinel Dashboard,默认端口为8080。Sentinel Dashboard启动后可以在浏览器中访问http://localhost:8080
查看Sentinel的管理界面。java -jar seata-server-1.5.0.jar -p 8091
启动Seata Server,默认端口为8091。Seata Server启动后可以在控制台查看服务状态。Nacos是一个动态服务发现、配置管理和服务管理平台。它可以帮助你在大规模服务架构中实现集中化配置、服务注册和发现。
spring: application: name: demo-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848
spring-cloud-starter-alibaba-nacos-discovery
依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
@EnableDiscoveryClient
注解:import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
NacosDiscoveryProperties
获取服务列表:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.stereotype.Component; @Component public class ServiceDiscovery implements ApplicationRunner { @Autowired private DiscoveryClient discoveryClient; @Override public void run(ApplicationArguments args) throws Exception { List<String> services = discoveryClient.getServices(); System.out.println("Discovered services: " + services); } }
RestTemplate
进行远程服务调用:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ServiceController { @Autowired private RestTemplate restTemplate; @GetMapping("/call-service") public String callService() { return restTemplate.getForObject("http://demo-service/hello", String.class); } }
application.yml
中配置ribbon
负载均衡器:spring: application: name: demo-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 ribbon: NFLoadBalancerClassName: com.netflix.loadbalancer.RoundRobinLoadBalancer
Sentinel是阿里巴巴开源的流量控制组件,可以对微服务流量进行限流、降级和系统负载保护。
pom.xml
中添加Sentinel依赖:<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-spring-cloud-alibaba</artifactId> <version>1.8.2</version> </dependency>
spring: cloud: sentinel: transport: dashboard: localhost:8080
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.alibaba.csp.sentinel.annotation.SentinelResource; @SpringBootApplication @EnableDiscoveryClient public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
@SentinelResource
注解保护服务方法:import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; @RestController public class ServiceController { @GetMapping("/test") @SentinelResource(value = "testResource", blockHandler = "handleException") public String test() { return "Hello Sentinel!"; } public String handleException(BlockException ex) { return "Blocked by Sentinel!"; } }
Seata是一个致力于微服务分布式事务的开源项目,提供高性能和易于集成的分布式事务解决方案。
pom.xml
中添加Seata依赖:<dependency> <groupId>com.github.alipay</groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.5.0</version> </dependency>
seata: application-id: demo-app tx-service-group: default server: ip: 127.0.0.1 port: 8091
java -jar seata-server-1.5.0.jar -p 8091
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.seata.core.context.RootContext; import io.seata.spring.annotation.GlobalTransactional; @RestController public class ServiceController { @Autowired private DemoService demoService; @GetMapping("/testTransaction") @GlobalTransactional public String testTransaction() { demoService.testTransaction(); return "Transaction succeeded!"; } }
Service
类中使用@GlobalTransactional
注解:import org.springframework.stereotype.Service; import io.seata.spring.annotation.GlobalTransactional; @Service public class DemoService { @GlobalTransactional public void testTransaction() { // 业务逻辑 } }SpringCloud Alibaba入门案例
在本案例中,我们将创建两个服务:service-provider
和service-consumer
,并通过Nacos实现服务注册与发现。
service-provider
服务service-provider
。spring-cloud-starter-alibaba-nacos-discovery
依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
application.yml
:spring: application: name: service-provider cloud: nacos: discovery: server-addr: 127.0.0.1:8848
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class ServiceProviderApplication { public static void main(String[] args) { SpringApplication.run(ServiceProviderApplication.class, args); } }
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ProviderController { @GetMapping("/hello") public String hello() { return "Hello from service-provider!"; } }
service-consumer
服务service-consumer
。spring-cloud-starter-alibaba-nacos-discovery
依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
application.yml
:spring: application: name: service-consumer cloud: nacos: discovery: server-addr: 127.0.0.1:8848
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDiscoveryClient public class ServiceConsumerApplication { public static void main(String[] args) { SpringApplication.run(ServiceConsumerApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ConsumerController { @Autowired private RestTemplate restTemplate; @GetMapping("/call-service") public String callService() { return restTemplate.getForObject("http://service-provider/hello", String.class); } }
在本案例中,我们将保护一个微服务接口,使用Sentinel进行流量控制。
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-spring-cloud-alibaba</artifactId> <version>1.8.2</version> </dependency>
spring: cloud: sentinel: transport: dashboard: localhost:8080
@SentinelResource
注解保护接口:import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; @RestController public class ServiceController { @GetMapping("/test") @SentinelResource(value = "testResource", blockHandler = "handleException") public String test() { return "Hello Sentinel!"; } public String handleException(BlockException ex) { return "Blocked by Sentinel!"; } }
java -jar sentinel-dashboard-1.8.2.jar
在本案例中,我们将使用Seata实现分布式事务。
<dependency> <groupId>com.github.alipay</groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.5.0</version> </dependency>
seata: application-id: demo-app tx-service-group: default server: ip: 127.0.0.1 port: 8091
java -jar seata-server-1.5.0.jar -p 8091
@GlobalTransactional
注解:import org.springframework.stereotype.Service; import io.seata.spring.annotation.GlobalTransactional; @Service public class DemoService { @GlobalTransactional public void testTransaction() { // 业务逻辑 } }SpringCloud Alibaba微服务配置
Nacos不仅用来注册和发现服务,还可以用来做集中化的配置管理。通过Nacos,可以方便地管理和动态刷新微服务的配置。
pom.xml
中添加Nacos配置中心依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
application.yml
:spring: application: name: demo-config cloud: nacos: config: server-addr: 127.0.0.1:8848 file-extension: yaml
在Nacos服务中创建配置文件:
demo-config
,数据ID设置为demo-config.properties
,配置内容为foo=bar
。import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class ConfigDemo implements ApplicationRunner { @Value("${foo}") private String foo; @Override public void run(ApplicationArguments args) throws Exception { System.out.println("Config value: " + foo); } }
Nacos提供了一个动态刷新配置的功能,可以在不重启应用的情况下刷新配置。
pom.xml
中添加spring-cloud-starter-alibaba-nacos-config
依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
bootstrap.yml
:spring: cloud: nacos: config: server-addr: 127.0.0.1:8848 file-extension: yaml refresh-enabled: true
@RefreshScope
注解标识需要动态刷新的Bean:import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @Component @RefreshScope public class ConfigDemo { @Value("${foo}") private String foo; public String getFoo() { return foo; } }
POST /actuator/refresh
接口刷新配置:curl -X POST http://localhost:8080/actuator/refresh
在Spring Cloud Alibaba中,可以使用Nacos作为配置中心来管理微服务的配置。
pom.xml
中添加依赖:<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
application.yml
:spring: application: name: demo-config cloud: nacos: config: server-addr: 127.0.0.1:8848 file-extension: yaml
在Nacos服务中创建配置文件demo-config.properties
,配置内容为foo=bar
。
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class ConfigDemo implements ApplicationRunner { @Value("${foo}") private String foo; @Override public void run(ApplicationArguments args) throws Exception { System.out.println("Config value: " + foo); } }SpringCloud Alibaba常见问题及解决方法
logs
目录下,可以找到异常信息。服务注册失败
application.yml
配置,确保server-addr
正确。@EnableDiscoveryClient
注解被正确使用。服务调用失败
RestTemplate
配置是否正确。Sentinel规则配置问题
@SentinelResource
注解的配置是否正确。@GlobalTransactional
注解的配置是否正确。通过上述详细的步骤和示例代码,你可以快速搭建和使用SpringCloud Alibaba开发微服务应用,并学习到如何使用Nacos、Sentinel和Seata等核心组件。希望这些内容对你有所帮助!