赞
踩
springcloud gateway是springcloud全家桶的一个组件之一,替代了之前zuul。springcloud gateway组件的功能很强大,可以让我们很容易实现路由,白名单,限流,鉴权等功能,对于微服务系统来说,gateway就是系统的门户,是必不可少的一环。
注:这里贴出来的是部分关键依赖,篇幅有限,详情请下载源码:https://gitee.com/superamxing/simple-demo
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-openfeign-core</artifactId> </dependency>
添加好依赖,然后再启动类上加上@EnableFeignClients,@EnableDiscoveryClient,@SpringBootApplication三个注解,分别是开启Feign客户端,服务注册和Springboot程序的核心注解:
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class LibraryGatewayApplication {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(LibraryGatewayApplication.class, args);
}
}
然后再启动一个项目library-client,以/api/user/login接口为例,在网关项目的yml文件中添加如下配置,具体gateway的路由功能需要大家参考官方文档来钻研学习:
server: port: 8888 spring: cloud: nacos: discovery: server-addr: ${NACOS_HOST}:${NACOS_PORT} config: server-addr: ${NACOS_HOST}:${NACOS_PORT} file-extension: yml username: nacos password: nacos gateway: discovery: locator: enabled: true routes: - id: library-client uri: lb://library-client predicates: - Path=/library-client/api/** filters: - StripPrefix=1 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/db_library?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC username: root password: root application: name: library-gateway
分别启动好两个项目,网管项目library-gateway和客户端项目library-client
然后我们直接可以通过调用网关服务(服务端口为8888),然后路由到library-client.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。