springcloudalibaba怎么使用代码示例
时间: 2023-09-22 16:12:01 浏览: 90
以下是一个简单的springcloudalibaba示例:
1. 添加Maven依赖
在pom.xml文件中添加以下依赖:
```xml
<dependencies>
<!-- Spring Cloud Alibaba Core -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
</dependencies>
```
2. 配置Nacos服务地址
在application.properties文件中添加以下配置:
```
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
```
3. 创建服务提供者
创建一个简单的RESTful服务提供者:
```java
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
```
4. 启动服务提供者
在服务提供者的main方法中添加@EnableDiscoveryClient注解,并启动应用程序:
```java
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
```
5. 创建服务消费者
创建一个简单的服务消费者:
```java
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consume")
public String consume() {
return restTemplate.getForObject("http://provider/hello", String.class);
}
}
```
6. 配置RestTemplate
在服务消费者的配置类中添加以下配置:
```java
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
```
7. 启动服务消费者
在服务消费者的main方法中启动应用程序:
```java
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
```
8. 访问服务
启动服务提供者和服务消费者后,访问http://localhost:8081/consume即可看到"Hello, world!"的输出。
阅读全文
相关推荐
















