SpringCloud項目開發入門:新手必讀指南
SpringCloud项目开发入门涉及Spring Boot和微服务框架的集成,帮助开发者快速构建松耦合、易于管理的微服务应用。文章将详细介绍SpringCloud环境搭建、核心组件使用及实战项目构建,帮助新手快速上手。
SpringCloud项目开发入门:新手必读指南 SpringCloud简介与环境搭建SpringCloud是什么
Spring Cloud 是一套基于 Spring Boot 实现的微服务框架,它为开发者提供了快速构建分布式系统的工具箱。Spring Cloud 是市面上最受欢迎的微服务框架之一,它可以帮助开发者快速构建松耦合、易于管理的微服务应用。Spring Cloud的核心优势在于它能够与 Spring Boot无缝集成,使得开发者可以快速地在 Spring Boot 应用程序中实现分布式系统中的常见模式。
开发环境准备
在开发 Spring Cloud 应用之前,需要确保安装了以下几个软件:
- JDK 1.8 或更高版本
- Maven 3.0 或更高版本
- IntelliJ IDEA 或 Eclipse 等 IDE
- Git 版本控制系统(可选)
安装完这些软件后,通过命令行创建一个 Maven 项目,示例如下:
mvn archetype:generate -DgroupId=com.example -DartifactId=springcloud-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
然后在项目根目录下创建一个 pom.xml
文件,用于管理项目依赖:
<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>springcloud-demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2021.0.4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
快速入门示例
下面是一个简单的 Spring Cloud 示例,包括服务提供者和服务消费者。服务提供者将提供一个简单的 RESTful API,服务消费者将调用这个 API。
服务提供者(Provider)
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class GreetingController {
@GetMapping("/hello")
public String greeting() {
return "Hello, world!";
}
}
服务消费者(Consumer)
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
// src/main/java/com/example/demo/service/DemoService.java
package com.example.demo.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "demo-provider", url = "http://localhost:8080")
public interface DemoService {
@GetMapping("/hello")
String greeting();
}
// src/main/java/com/example/demo/controller/DemoController.java
package com.example.demo.controller;
import com.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Autowired
private DemoService demoService;
@GetMapping("/greeting")
public String greeting() {
return demoService.greeting();
}
}
SpringCloud核心组件介绍
Eureka服务注册与发现
Eureka 是 Netflix 开发的一个服务注册与发现组件。它提供服务注册和发现的功能,使服务提供者和消费者之间能够互相发现。服务提供者在启动时注册自身信息,服务消费者在调用时从 Eureka 注册中心获取服务提供者列表。
服务提供者
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class GreetingController {
@GetMapping("/hello")
public String greeting() {
return "Hello, world!";
}
}
服务消费者
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Ribbon负载均衡
Ribbon 是 Netflix 开发的客户端负载均衡工具,它主要用来在服务消费者调用服务提供者时,从服务提供者列表中选择一个合适的服务实例进行调用。
服务消费者配置
// src/main/resources/application.yml
spring:
application:
name: demo-consumer
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
feign:
okhttp:
enabled: true
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
Hystrix断路器
Hystrix 是 Netflix 开发的一款用于处理分布式服务架构中的延迟和容错的开源库。它主要用于处理依赖服务失败的情况,防止级联故障,保证系统整体的可用性。
服务消费者配置
// src/main/java/com/example/demo/service/DemoService.java
package com.example.demo.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "demo-provider", url = "http://localhost:8080")
public interface DemoService {
@GetMapping("/hello")
String greeting();
}
// src/main/resources/application.yml
spring:
application:
name: demo-consumer
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
feign:
okhttp:
enabled: true
hystrix:
enabled: true
实战项目:构建微服务应用
创建服务提供者
服务提供者为其他服务提供功能实现。例如,假设有一个服务提供者提供用户信息查询的逻辑。
服务提供者配置
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController
class UserServiceController {
@GetMapping("/user/{id}")
public String getUserById(String id) {
return "User " + id;
}
}
启动类
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
创建服务消费者
服务消费者是调用服务提供者的客户端应用。
服务消费者配置
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
// src/main/java/com/example/demo/service/UserService.java
package com.example.demo.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "user-service-provider", url = "http://localhost:8080")
public interface UserService {
@GetMapping("/user/{id}")
String getUserById(String id);
}
// src/main/java/com/example/demo/controller/UserController.java
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public String getUserById(@PathVariable String id) {
return userService.getUserById(id);
}
}
配置服务注册与发现
为了让服务提供者和消费者可以互相发现,需要在服务提供者和消费者中配置 Eureka 注册中心。
服务提供者配置
# src/main/resources/application.yml
spring:
application:
name: user-service-provider
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
服务消费者配置
# src/main/resources/application.yml
spring:
application:
name: user-service-consumer
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
SpringCloud配置中心使用
配置中心简介
Spring Cloud Config 为 Spring Boot 应用程序提供了集中式的外部配置管理。Config 服务器可以从诸如 Git 等存储库中加载配置文件,并将其作为属性提供给客户端应用程序。这样,你可以轻松地管理各种环境(开发、测试、生产)下的配置,而不需要将配置硬编码到代码中。
配置中心搭建
首先,搭建一个 Spring Cloud Config Server 作为配置中心。
Config Server 项目
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
// src/main/java/com/example/configserver/ConfigServerApplication.java
package com.example.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
Config Server 配置
# src/main/resources/application.yml
spring:
cloud:
config:
server:
git:
uri: https://github.com/your-repo/config-repo
username: your-username
password: your-password
server:
port: 8888
然后,创建一个客户端 Config Client 来消费配置中心的配置。
Config Client 项目
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
# src/main/resources/bootstrap.yml
spring:
application:
name: demo-app
cloud:
config:
uri: http://localhost:8888
// src/main/java/com/example/configclient/ConfigClientApplication.java
package com.example.configclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
@RestController
@RefreshScope
class ConfigController {
@GetMapping("/config")
public String getConfig() {
return "Hello, world!";
}
}
动态刷新配置
Spring Cloud Config 支持配置的动态刷新,使得应用程序可以在不重启的情况下获取最新的配置。
配置刷新
// src/main/java/com/example/configclient/ConfigClientApplication.java
package com.example.configclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
@RestController
@RefreshScope
class ConfigController {
@GetMapping("/config")
public String getConfig() {
return "Hello, world!";
}
}
在 Config Client 中添加 @RefreshScope
注解,以便客户端可以自动刷新配置。
网关简介
Spring Cloud Gateway 是一个基于 Spring Framework 5.0、Project Reactor 和 Spring Boot 2.0 构建的 API 网关。它能够实现动态路由、过滤器、断路器等功能。通过使用 Gateway,你可以轻松地将所有入站请求路由到适当的服务。
网关搭建与配置
网关项目
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
// src/main/java/com/example/gateway/GatewayApplication.java
package com.example.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
网关配置
# src/main/resources/application.yml
spring:
application:
name: gateway-service
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring:
cloud:
gateway:
routes:
- id: demo_route
uri: lb://demo-consumer
predicates:
- Path=/hello/**
路由规则解析
为了更好地理解路由规则,我们可以通过配置不同的路由规则来实现不同的路由效果。
路径匹配
spring:
cloud:
gateway:
routes:
- id: path_route
uri: lb://demo-consumer
predicates:
- Path=/path/**
Host 匹配
spring:
cloud:
gateway:
routes:
- id: host_route
uri: lb://demo-consumer
predicates:
- Host=example.com
Header 匹配
spring:
cloud:
gateway:
routes:
- id: header_route
uri: lb://demo-consumer
predicates:
- Header=X-Request-Id, \d+
SpringCloud安全与认证
安全性简介
Spring Security 是一个强大而灵活的安全框架,提供认证和授权的功能。Spring Security 与 Spring Boot 结合使用可以方便地实现安全性功能。
OAuth2认证
OAuth2 是一种授权框架,它允许用户在不暴露他们的密码的情况下授权第三方应用访问他们的资源。Spring Security OAuth2 提供了完整的 OAuth2 支持。
OAuth2 服务器项目
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
# src/main/resources/application.yml
spring:
security:
oauth2:
client:
registration:
demo:
client-id: your-client-id
client-secret: your-client-secret
scope: read,write
authorization-grant-type: authorization_code
redirect-uri: http://localhost:8081/callback
provider:
demo:
authorization-uri: http://localhost:8080/oauth/authorize
token-uri: http://localhost:8080/oauth/token
user-info-uri: http://localhost:8080/userinfo
user-name-attribute: sub
OAuth2 客户端项目
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
# src/main/resources/application.yml
spring:
security:
oauth2:
client:
registration:
demo:
client-id: your-client-id
client-secret: your-client-secret
scope: read,write
authorization-grant-type: authorization_code
redirect-uri: http://localhost:8081/callback
provider:
demo:
authorization-uri: http://localhost:8080/oauth/authorize
token-uri: http://localhost:8080/oauth/token
user-info-uri: http://localhost:8080/userinfo
user-name-attribute: sub
// src/main/java/com/example/oauth2/OAuth2Application.java
package com.example.oauth2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
@SpringBootApplication
@EnableEurekaClient
@EnableOAuth2Client
public class OAuth2Application {
public static void main(String[] args) {
SpringApplication.run(OAuth2Application.class, args);
}
}
JWT令牌介绍
JWT(JSON Web Token)是一种开放标准(RFC 7519),它定义了一种紧凑、自包含的方法,用于在各方之间安全地传输信息。JWT 通常用于身份验证,可以用来替代传统的 Cookie 方式。
使用 Spring Security 进行 JWT 验证
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
# src/main/resources/application.yml
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080
oauth2:
token-type: bearer
format: jwt
client-id: client
client-secret: secret
// src/main/java/com/example/jwt/JwtApplication.java
package com.example.jwt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
@SpringBootApplication
@EnableResourceServer
public class JwtApplication extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**")
.authenticated()
.and()
.oauth2ResourceServer()
.jwt();
}
public static void main(String[] args) {
SpringApplication.run(JwtApplication.class, args);
}
}
JWT token生成
// src/main/java/com/example/jwt/TokenService.java
package com.example.jwt;
import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;
public class TokenService {
public static String generateToken(String id) throws JoseException {
// Generate JWT token
JWSHeader jwtHeader = new JWSHeader(JWSAlgorithm.HS256);
Payload jwtPayload = new Payload(id);
JWSSigner signer = new MacSigner("secret");
JWSObject jwsObject = new JWSObject(jwtHeader, jwtPayload);
jwsObject.sign(signer);
return jwsObject.serialize();
}
}
以上就是 Spring Cloud 初学者指南的全部内容,希望对你的项目开发有所帮助。如果你想要了解更多 Spring Cloud 的高级功能,可以访问 Spring Cloud 官方文档 或者 慕课网。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章