Spring Cloud 整合
Spring Cloud 整合指的是将Spring Cloud微服务组件整合在一起。以下是一个简单的Spring Cloud整合示例,包括Eureka服务注册中心、一个服务提供者和一个服务消费者。
- 创建Eureka服务注册中心:
@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/
- 创建服务提供者:
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServiceProviderApplication {
@Value("${server.port}")
private String port;
@GetMapping("/hello")
public String hello() {
return "Hello from port: " + port;
}
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/
- 创建服务消费者:
@SpringBootApplication
@EnableEurekaClient
@RestController
public class ServiceConsumerApplication {
@Autowired
private RestTemplate restTemplate;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("/call-service")
public String callService() {
return restTemplate.getForObject("http://localhost:8080/hello", String.class);
}
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/
启动Eureka服务注册中心,然后启动服务提供者和服务消费者。服务提供者将注册到Eureka服务注册中心,服务消费者可以通过Eureka发现服务并调用它。
评论已关闭