SpringCloud-Zuul实战(一)

springboot2.0.3+cloud Finchley.RELEASE版本先保持统一

  1. pom
 <dependencies>
        <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
        <version>1.3.4.RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. yml配置
server:
  port: 8050      
spring:
  application:
    name: gateway-zuul      
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
zuul:
  ignoredServices: '*'
  routes:
    app-a:
      path: /we1/**
      serviceId: CART-PROVIDER

其中path是代理路由,serviceID是其他服务在eureka注册的服务名

  1. 自定义Filter
    可以基于此Filter实现鉴权,限流,日志等操作
@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";//前置
    }
    @Override
    public int filterOrder() {
        return 0;//优先级,越小越级别高
    }
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest servletRequest = context.getRequest();
        //请求特定url时执行鉴权
        if ("/we1/cart/query".equals(servletRequest.getRequestURI())){
            return true;
        }
        return false;
    }
    //如何鉴权
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest servletRequest = context.getRequest();
		//这里前端会在header中放入token
        String authorization = servletRequest.getHeader("authorization");
        //	1.header中没有token
        //	2.token不正确(可以从redis查其是否有效)
        if (authorization==null||!"token123456".equals(authorization)){//假设设备token为token123456
            System.err.println("token is not right");
            context.setSendZuulResponse(false); //这不予放行
            context.setResponseStatusCode(205);  //返回一个http状态码
        }
        return null;
    }
}
  1. 启动类+注册FilterBean
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }
    
    @Bean
    public AuthFilter getAuth(){
        return  new AuthFilter();
    }

}

5.测试 postman中header加入token

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值