SpringCloud 项目搭建(六):服务路由网关搭建

六、服务路由网关

1.在父项目上面新建模块myzuul


2.选择Spring Cloud Discovery—>Eureka Discovery Client
选择Spring Cloud Routing—>Zuul


3.Module Name一般不做修改,和项目名称Artifact一样

 
4.将src\main\resources下面的application.properties改名为application.yml,修改文件编码方式为UTF-8,内容如下

server:
  port: 1003
spring:
  application:
    name: myzuul
  profiles:
    active: default
  zipkin:
     enabled: true
     base-url: http://localhost:9411/
     locator:
       discovery:
         enabled: true
     sender:
       type: WEB
  sleuth:
     web:
       client:
         enabled: true
     sampler:
       # 默认的采样比率为0.1,不能看到所有请求数据
       # 更改采样比率为1,就能看到所有的请求数据了,但是这样会增加接口调用延迟
       probability: 1.0
eureka:
  instance:
    lease-renewal-interval-in-seconds: 5      # 心跳时间,即服务续约间隔时间 (缺省为30s)
    lease-expiration-duration-in-seconds: 10  # 没有心跳的淘汰时间,10秒,即服务续约到期时间(缺省为90s)
    prefer-ip-address: true                   # 将IP注册到服务注册中心
  client:
    service-url:
      defaultZone: http://localhost:1024/eureka/
    fetch-registry: true # 向注册中心注册
    registry-fetch-interval-seconds: 5 # 服务清单的缓存更新时间,默认30秒一次
zuul:
  ignored-services: "*"
  strip-prefix: true  #请求转发时去掉转发路径(path中的值)
  routes:
    myservice:  #所有以/api开头的请求都转发到myservice服务
      path: /api/**
      serviceId: myservice


5.pom文件中增加依赖,并在Maven Projects里面刷新

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

6.打开src\main\java\com\li\myzuul下面的MyzuulApplication.java

在启动类上加入@EnableZuulProxy注解,开启zuul。

@EnableZuulProxy
@SpringBootApplication
public class MyzuulApplication {

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

}

7.打开浏览器访问http://localhost:1003/api/getTime


8.增加安全验证,在src\main\java\com\li\myzuul下面新建包filter,新建MyFilter.java

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        log.info("ok");
        return null;
    }
}
 
8.打开浏览器访问http://localhost:1003/api/getTime?token=22

猜你喜欢

转载自www.cnblogs.com/liw66/p/12298346.html