Spring Cloud
今天我开始学习Spring Cloud的第一天,了解了什么是Spring Cloud,以及Spring Cloud的核心组件和功能。
首先,我们需要创建一个Eureka Server,用于服务的注册和发现。
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
然后,我们需要创建一个服务提供者,将其注册到Eureka Server上。
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
@RestController
class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
最后,我们需要创建一个服务消费者,从Eureka Server上发现服务,并调用服务提供者提供的服务。
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
@RestController
class HelloController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/hello")
public String hello() {
String url = "http://provider-service/hello";
return restTemplate.getForObject(url, String.class);
}
}
@Configuration
class Config {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
以上三个应用中,Eureka Server用于服务注册和发现,服务提供者提供服务并将服务注册到Eureka Server上,服务消费者从Eureka Server上发现服务,并调用服务提供者提供的服务。