Spring Cloud Zuul入门

3 篇文章 0 订阅
3 篇文章 0 订阅

首先配置好2个服务,一个用于登录的login-server,一个用来测试的test-server,具体逻辑代码自己写,这里要注意的一点是,按照Zuul的思想是:只做服务的转发,不做页面的转发。也就是说只做RestController注解的Mapping,不做View的跳转,当然,要跳转的话也是可以的,没啥区别,但是不符合Zuul的思想,这个的话看个人。页面跳转如果没有做前后端分离,可以放置在一个专门的服务里面,通过JSON值确定是否为跳转页面。

Zuul的配置文件

server:
  port: 8111
spring:
  profiles: zuul
  application:
    name: zuul-server

eureka:
  client:
    service-url:
      # eureka的URL
      defaultZone: http://127.0.0.1:8001/eureka/,http://127.0.0.1:8002/eureka/
  instance:
    hostname: 127.0.0.1
    preferIpAddress: true
zuul:
  sensitiveHeaders:
  ignored-patterns: '*'
  routes:
    competition-manage-web-server:
      path: /login/**
      service-id: login-server
      strip-prefix: false
    competition-manage-sso-server:
      path: /test/**
      service-id: test-server
      strip-prefix: false

pom.xml文件:

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
    </dependencies>

启动类:

@EnableEurekaClient
@EnableZuulProxy
@EnableDiscoveryClient
@SpringBootApplication
public class ZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class,args);
    }
}

ZuulFilter过滤器:

@Component
public class HttpRequestFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -4;
    }

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

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = CookieUtils.getCookie(request, "token");
        HttpServletResponse response = context.getResponse();
        // 剔除登录的url
        String[] notFilter = new String[]{"/login/login","/login/"};
        String uri = request.getRequestURI();
        System.out.println(uri);
        for (String str : notFilter) {
            if(uri.contains(str)){
                context.setResponseStatusCode(HttpStatus.OK.value());
                return null;
            }
        }
        if(StringUtil.isNull(token)){
            // 表示没有携带token,必须登录
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            context.setResponseBody(HttpStatus.UNAUTHORIZED.getReasonPhrase());
            context.setSendZuulResponse(false);
            try {
                response.sendRedirect("/login/");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
        return null;
    }
}

CookieUtils文件:

    /**
     * 设置Cookie
     * @param response 响应参数
     * @param token 令牌Key
     * @param value 令牌对应的值Value
     */
    public static void setCookie(HttpServletResponse response, String token, String value){
        Cookie cookie = new Cookie(token,value);
        cookie.setMaxAge(15 * 60);// 15分钟过期
        cookie.setPath("/");
        cookie.setVersion(1);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    /**
     * 读取Cookie
     * @param request 请求参数
     * @param token 令牌Key
     */
    public static String getCookie(HttpServletRequest request, String token){
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return null;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if(!StringUtil.isNull(name) && name.equals(token)){
                return cookie.getValue();
            }
        }
        return null;
    }

为了保证Cookie的信息能够共享(解决跨域问题,localhost:8011到localhost:8111就是跨域了)使用Nginx作为反向代理服务器,保证Cookie信息共享

nginx.conf文件:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    server {
        listen       80;
        server_name  localhost;

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Cookie,Set-Cookie,x-requested-with,content-type';

		#####登录服务######
		location /login{
			proxy_pass http://localhost:8011;
			proxy_cookie_path  /login/ /;  ##Cookie共享
			proxy_set_header   Host    $host;
			proxy_set_header   X-Real-IP   $remote_addr;
			proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
		}
		#####其他服务#######
		location / {
			proxy_pass http://localhost:8111;###走Zuul
			proxy_cookie_path  /;  ##Cookie共享
			proxy_set_header   Host    $host;
			proxy_set_header   X-Real-IP   $remote_addr;
			proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
		}
    }

}

其他的两个服务都比较简单,仅仅是一个Demo而已,并不需要很复杂,登录之后把token存入Cookie中。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值