聊一下分布式与微服务Spring Cloud
Spring Cloud是一个提供工具支持以快速、便捷方式构建分布式系统的Spring 框架。它包含了多个子项目,如Spring Cloud Config用于配置管理,Spring Cloud Netflix提供与Netflix开源软件的集成,比如Zuul路由,Hystrix服务间隔,Archaius配置等。
以下是一个简单的Spring Cloud微服务示例,使用Eureka作为服务注册与发现。
- 添加依赖到
pom.xml
:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置应用
application.properties
:
spring.application.name=demo-service
server.port=8080
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
- 启动类添加
@EnableDiscoveryClient
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class DemoServiceApplication {
public static void main(String[] args) {
SpringApplication.run(DemoServiceApplication.class, args);
}
}
- 创建一个REST控制器:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${spring.application.name}")
private String serviceName;
@GetMapping("/hello")
public String hello() {
return "Hello from " + serviceName;
}
}
以上代码创建了一个简单的Spring Boot应用,通过@EnableDiscoveryClient
注解将其注册到Eureka服务中心。然后提供了一个REST接口\`/hello
评论已关闭