微服务架构是一种架构模式,它提倡将单一应用程序划分成一组小的服务,这些服务都运行在自己的进程中,服务之间通过轻量级的通信机制互相协作。
Spring Cloud是一个提供工具支持以快速、便捷的方式实现微服务架构中一些常见模式的Spring子项目。
以下是一个简单的Spring Cloud示例,使用Spring Cloud Netflix的Eureka作为服务注册中心,以及Spring Cloud OpenFeign作为服务间调用的方式。
- 创建Eureka Server:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
application.properties:
spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
- 创建Service Provider:
@SpringBootApplication
@EnableEurekaClient
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
}
application.properties:
spring.application.name=service-provider
server.port=8080
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Service:
@RestController
public class ServiceController {
@GetMapping("/hello")
public String hello() {
return "Hello from Service Provider";
}
}
- 创建Service Consumer:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ServiceConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class, args);
}
}
application.properties:
spring.application.name=service-consumer
server.port=8081
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Feign Client:
@FeignClient("service-provider")
public interface ServiceProviderClient {
@GetMapping("/hello")
String hello();
}
Controller:
@RestController
public class ConsumerController {
@Autowired
private ServiceProviderClient serviceProviderClient;
@GetMapping("/call-service")
public String callService() {
return serviceProviderClient.hello();