SpringCloud实用篇02【Nacos配置管理+集群搭建+Feign远程调用+GateWay服务网关】
以下是一个简化的示例,展示了如何使用Spring Cloud Alibaba Nacos作为配置中心和服务注册中心,以及如何使用Feign进行远程调用和使用Gateway作为服务网关。
// 引入相关依赖
<dependencies>
<!-- Spring Cloud Alibaba Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Spring Cloud Alibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- Feign Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
// Nacos配置管理application.properties
spring.application.name=nacos-config-demo
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
// Nacos服务注册application.properties
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
// Feign客户端接口定义
@FeignClient("nacos-provider")
public interface ProviderClient {
@GetMapping("/hello")
String hello();
}
// 使用Feign的服务消费者
@RestController
public class ConsumerController {
@Autowired
private ProviderClient providerClient;
@GetMapping("/hello")
public String hello() {
return providerClient.hello();
}
}
// Gateway路由配置
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocator routeLocator) {
return routeLocator.routes()
.route("path_route", r -> r.path("/provider/**")
.filters(f -> f.stripPrefix(1))
.uri("lb://nacos-provider")
.order(0)
)
.build();
}
}
// 服务提供者启动类
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
// 服务消费者启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsumerApplication {
public static void main(String[] args) {
评论已关闭