springcloud2 gateway 之一:简单样例

据说springcloud自己的gateway比netflix的zuul租性能好,gateway有替代zuul的趋势

gateway可以对请求做相应处理,还可以对响应做相应处理,还可以做权限控制等等

gateway不仅能转发api接口请求,也能转发页面请求,返回页面。

一、gateway项目

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.urthink.upfs</groupId>
    <artifactId>springcloud-gateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springcloud-gateway</name>
    <description>springcloud-gateway project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

2. SpringcloudGatewayApplication.java

package com.urthink.upfs.springcloudgateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * http://localhost:8081/demo/test1
 * http://localhost:8080/app1/demo/test1
 */
@SpringBootApplication
public class SpringcloudGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringcloudGatewayApplication.class, args);
    }

}

3. application.yml

server:
  port: 8080


spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        #netty 路由过滤器,http或https开头
      - id: app1-route
        uri: http://localhost:8081
        predicates:
        - Path=/app1/**
        filters:
          #转发请求时去掉1级前缀
        - StripPrefix=1

把以/app1开头的请求,转发到http://localhost:8081

predicates是谓词,

Spring会根据名称去查找对应的FilterFactory,目前支持的名称有:After、Before、Between、Cookie、Header、Host、Method、Path、Query、RemoteAddr。

Spring-Cloud-Gateway之RoutePredicate
https://www.jianshu.com/p/03d42105f81f

008-spring cloud gateway-路由谓词RoutePredicate、RoutePredicateFactory
https://www.cnblogs.com/bjlhx/p/9785926.html

二、普通项目 springboot-demo

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.demo</groupId>
    <artifactId>springboot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-demo</name>
    <description>springboot-demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. SpringbootDemoApplication.java

package com.example.demo.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }

}

3. User.java

package com.example.demo.springbootdemo.entity;

import java.io.Serializable;

public class User implements Serializable {

    private Integer id;

    private String name;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

4. DemoController.java

package com.example.demo.springbootdemo.controller;


import com.example.demo.springbootdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 测试Controller
 *
 * @author zhao
 * @date 2019.3.8
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

    //返回数据
    @RequestMapping(value = "/test1", method = RequestMethod.GET)
    @ResponseBody
    public String test1(HttpServletRequest request) {
        System.out.println(request.getRequestURI()); // /demo/test1
        return "返回数据";
    }


    //返回页面
    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public String test2(HttpServletRequest request) {
        System.out.println(request.getRequestURI()); // /demo/test2
        return "test";
    }

    //返回对象
    @RequestMapping(value = "/test3", method = RequestMethod.GET)
    @ResponseBody
    public User test3(HttpServletRequest request) {
        System.out.println(request.getRequestURI()); // /demo/test3
        User user = new User();
        user.setId(1);
        user.setName("admin");
        return user;
    }


}

5. application.yml

server:
  port: 8081

spring:
  application:
    name: springboot-demo
  freemarker:
    #指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
    allow-request-override: true
    #指定HttpSession的属性是否可以覆盖controller的model的同名项
    allow-session-override: true
    #是否开启template caching.
    cache: true
    #设定Template的编码.
    charset: UTF-8
    #是否检查templates路径是否存在.
    check-template-location: true
    #设定Content-Type.
    content-type: text/html
    #是否允许mvc使用freemarker.
    enabled: true
    #设定所有request的属性在merge到模板的时候,是否要都添加到model中.
    expose-request-attributes: true
    #设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中.
    expose-session-attributes: true
    #设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
    expose-spring-macro-helpers: true
    #视图加载顺序
    order: 0
    #是否优先从文件系统加载template,以支持热加载,默认为true
    prefer-file-system-access: true
    #设定freemarker模板的前缀.
    #prefix:
    #指定RequestContext属性的名.
    request-context-attribute: request
    #设定FreeMarker keys.
    settings:
      #如果变量为null,转化为空字符串,比如做比较的时候按照空字符串做比较
      classic_compatible: true
      #去掉多余的空格,非常有用
      whitespace_stripping: true
      #模板更新时间,这里配置是1秒更新一次,正式环境设置为3600秒
      template_update_delay: 1
      #中国
      locale: zh_CN
      #编码utf8
      default_encoding: utf_8
      #url编码utf8
      url_escaping_charset: utf_8
      #显示日期格式
      date_format: yyyy-MM-dd
      #显示时间格式
      time_format: HH:mm:ss
      #显示日期时间格式
      datetime_format: yyyy-MM-dd HH:mm:ss
      #数字格式
      number_format: 0.######
      output_encoding: UTF-8
      #布尔型格式
      boolean_format: true,false
      #宏定义
      #auto_import="/common/index.ftl" as ui
      tag_syntax: auto_detect
    #设定模板的后缀.
    suffix: .ftl
    #设定模板的加载路径,多个以逗号分隔,默认: ["classpath:/templates/"]
    template-loader-path: classpath:/templates/
    #指定使用模板的视图列表. White list of view names that can be resolved.
    #view-names:

6. test.ftl

<html>
<head>
    <title>测试2</title>
</head>
<body>
返回页面
</body>
</html>

请求http://localhost:8080/app1/demo/test1
和请求http://localhost:8081/demo/test1
结果是一样的

发布了67 篇原创文章 · 获赞 11 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/haveqing/article/details/88424598