当前位置: 首页 > 知识库问答 >
问题:

Zuul Api网关映射错误的服务url(字符集)?

师成弘
2023-03-14

我试图创建微服务,但zuul api网关服务映射了错误的url。似乎这与编码问题有关。

Zuul应用程序。性质

spring.application.name=zuul-api-gateway
server.port=8765

eureka.client.service-url.default-zone=http://localhost:8761/eureka

服务application.yml

spring:
  application:
    name: car-service
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3307/car_service_db?useSSL=false
    username: root
    password: admin
  profiles:
    active: local
server:
  port: 8080

eureka:
  client:
    service-url:
      default-zone: http://localhost:8761/eureka

management:
  security:
    enabled: false

其他服务应用程序。yml

spring:
  application:
    name: company-service
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3307/company_service_db?useSSL=false
    username: root
    password: admin
server:
  port: 8081

eureka:
  client:
    service-url:
      default-zone: http://localhost:8761/eureka


management:
  security:
    enabled: false

尤里卡日志:

2018-02-11 00:02:41.204  INFO 22672 --- [nio-8761-exec-2] c.n.e.registry.AbstractInstanceRegistry  : Registered instance CAR-SERVICE/localhost:car-service:8080 with status UP (replication=false)
2018-02-11 00:02:58.469  INFO 22672 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
2018-02-11 00:03:06.468  INFO 22672 --- [nio-8761-exec-4] c.n.e.registry.AbstractInstanceRegistry  : Registered instance COMPANY-SERVICE/localhost:company-service:8081 with status UP (replication=false)
2018-02-11 00:03:26.139  INFO 22672 --- [nio-8761-exec-9] c.n.e.registry.AbstractInstanceRegistry  : Registered instance ZUUL-API-GATEWAY/localhost:zuul-api-gateway:8765 with status UP (replication=false)

还有祖尔日志

2018-02-11 00:03:35.037  INFO [zuul-api-gateway,6944cfba5180a640,6944cfba5180a640,false] 2132 --- [nio-8765-exec-1] o.s.c.n.zuul.web.ZuulHandlerMapping      : Mapped URL path [/car-servıce/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]
2018-02-11 00:05:06.872  INFO [zuul-api-gateway,773aa5fc779af5e6,773aa5fc779af5e6,false] 2132 --- [nio-8765-exec-3] o.s.c.n.zuul.web.ZuulHandlerMapping      : Mapped URL path [/company-servıce/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]
2018-02-11 00:05:06.873  INFO [zuul-api-gateway,773aa5fc779af5e6,773aa5fc779af5e6,false] 2132 --- [nio-8765-exec-3] o.s.c.n.zuul.web.ZuulHandlerMapping      : Mapped URL path [/zuul-apı-gateway/**] onto handler of type [class org.springframework.cloud.netflix.zuul.web.ZuulController]

在zuul日志中,所有服务都通过带有土耳其语字符“i”的特殊字母映射,而我无法通过zuul api网关访问我的服务。

在本例中,我还尝试了覆盖Zuul配置:SpringCloudZUUL在转发的多部分请求文件名中中断UTF-8符号

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    FormBodyWrapperFilter formBodyWrapperFilter() {
        return new FormBodyWrapperFilter(new MyFormHttpMessageConverter());
    }

    private class MyFormHttpMessageConverter extends FormHttpMessageConverter {

        private byte[] getAsciiBytes(String name) {
            try {
                // THIS IS THE ONLY MODIFICATION:
                return name.getBytes("UTF-8");
            } catch (UnsupportedEncodingException ex) {
                // Should not happen - US-ASCII is always supported.
                throw new IllegalStateException(ex);
            }
        }
    }
}

所以,当我尝试通过ZuulAPI网关调用服务时,它返回404NotFound。

我正在使用SpringBoot2.0.0。M3,春云芬奇利。M2版本

共有3个答案

吴涵育
2023-03-14

您可以在Zuul应用程序的主方法中添加Locale.set默认为英语。

public static void main(String[] args) {
    Locale.setDefault(new Locale("en", "US"));
    SpringApplication.run(ServerApplication.class, args);
}

它也解决了你的问题。

慕容文昌
2023-03-14

我通过为toLowerCase(Locale.ROOT)选项创建扩展的EurekaDiscoveryClient解决了这个问题。

import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class CustomEurekaDiscoveryClient extends EurekaDiscoveryClient implements DiscoveryClient {


    private final EurekaInstanceConfig config;

    private final EurekaClient eurekaClient;

    public CustomEurekaDiscoveryClient(EurekaInstanceConfig config, @Qualifier("eurekaClient") EurekaClient eurekaClient) {
        super(config, eurekaClient);
        this.config = config;
        this.eurekaClient = eurekaClient;
    }

    @Override
    public List<String> getServices() {
        Applications applications = this.eurekaClient.getApplications();
        if (applications == null) {
            return Collections.emptyList();
        }
        List<Application> registered = applications.getRegisteredApplications();
        List<String> names = new ArrayList<>();
        for (Application app : registered) {
            if (app.getInstances().isEmpty()) {
                continue;
            }
            names.add(app.getName().toLowerCase(Locale.ROOT));

        }
        return names;
    }
}

在土耳其操作系统和jvm中,大小写“我”转换为小写“我”,而不是“我”,这就是为什么我需要覆盖公共列表getServices()方法。

如果toLowerCase(Locale.ROOT)方法调用时没有区域设置。根java将字符转换为“ı”,但使用区域设置。根选项,方法转换为“i”,项目运行良好。

穆承运
2023-03-14

当您使用SpringBoot时,我建议您使用ZuulGateway的注释,并为zuul创建定制过滤器,以处理每一件事情。

请找到下面的代码,看看它是否适用于您:

主类

@EnableZuulProxy
@SpringBootApplication
@EnableScheduling
@EnableFeignClients(basePackages = { Constants.FEIGN_BASE_PACKAGE })
@ComponentScan(basePackages = { Constants.BASE_PACKAGE, Constants.LOGGING_PACKAGE })
@EntityScan(basePackages = { Constants.ENTITY_BASE_PACKAGE })
@EnableDiscoveryClient
public class GatewayInitializer {

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {

        Security.setProperty("networkaddress.cache.ttl", "30");
        ConfigurableApplicationContext context = SpringApplication.run(Initializer.class, args);

    }

祖尔滤波器

package com.sxm.aota.gateway.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.util.ReflectionUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;


/**
 * This CustomErrorFilter involve to handle ZuulException.
 */
public class CustomErrorFilter extends ZuulFilter {

    /** The logger. */
    private static final Logger logger = LoggerFactory.getLogger(CustomErrorFilter.class);
    /** The message source. */
    @Autowired
    private MessageSource messageSource;
    /** The properties. */
    @Autowired
    private Properties properties;

    /*
     * (non-Javadoc)
     * 
     * @see com.netflix.zuul.ZuulFilter#filterType()
     */
    @Override
    public String filterType() {
        return "post";
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.netflix.zuul.ZuulFilter#filterOrder()
     */
    @Override
    public int filterOrder() {
        return -1; // Needs to run before SendErrorFilter which has filterOrder == 0
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.netflix.zuul.IZuulFilter#shouldFilter()
     */
    @Override
    public boolean shouldFilter() {
        // only forward to errorPath if it hasn't been forwarded to already
        return RequestContext.getCurrentContext().containsKey("error.status_code");
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.netflix.zuul.IZuulFilter#run()
     */
    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            Object e = ctx.get("error.exception");
            if (e != null && e instanceof ZuulException) {
                ZuulException zuulException = (ZuulException) e;
                logger.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);
                // Remove error code to prevent further error handling in follow up filters
                ctx.remove("error.status_code");

                } else {
                    error.setMessage(messageSource.getMessage(Constants.REQUESTED_SERVICE_UNAVAILABLE, new Object[] { zuulException.getCause() }, properties.getCurrentLocale()));
                    ctx.setResponseBody(mapper.writeValueAsString(error));
                    ctx.getResponse().setContentType("application/json");
                    ctx.setResponseStatusCode(500); // Can set any error code as excepted
                }
            }
        } catch (Exception ex) {
            logger.error("Exception filtering in custom error filter", ex);
            ReflectionUtils.rethrowRuntimeException(ex);
        }
        return null;
    }
}
 类似资料:
  • 我是spring cloud Gateway的新手。我有以下场景: 我在找建议。 提前道谢。

  • 这个log比较多 2015-03-30 10:49:49,679 org.nutz.mvc.impl.Loadings.scanModules(Loadings.java:98) DEBUG - module class location 'file:/D:/nutzbook/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp

  • 我正在开发一个包含以下模块的spring微服务体系结构(参见下面的体系结构图): 配置服务器 尤里卡服务器 Zuul Api网关 user-api(配置服务器客户端,Eureka-Client) Stats-api(配置服务器客户端,Eureka-Client) Auth-Service(进行中/断章取义) 这更多的是一种配置方法,而不是一个bug。到目前为止一切正常。对于大多数核心API的配置,

  • 我在项目中使用Java、Eclipse和Ant。我有一些Java代码需要编辑并在其中添加一些UTF-8字符。以前是我的身材。xml:而且它工作得很好。现在,在我尝试运行时添加这些UTF-8字符之后,它抛出“错误:编码Cp1252的不可映射字符” 谁能告诉我解决办法是什么?我试图改变编码UTF-8和cp1252在xml但没有运气。 我使用的是JRE7、Eclipse开普勒和蚂蚁4.11。

  • Nutz.Mvc 的核心任务就是将 HTTP 请求的 URL 映射到某一个入口函数,如果你看完了 Nutz.Mvc 概述 你大概应该知道,映射的配置信息是通过注解 @At 来设置的,@At 注解也非常简单,配置起来应该没有什么障碍。 但是,依然在某些时候,你会在你的应用出现 404 错误,为了能让你在编写项目是,心里非常有底,这里将详细的解释一下 JSP/Servlet 以及 Nutz.Mvc 映

  • 现在我们已经有了前面章节中解释的工作视图。 我们想通过URL访问该视图。 Django有自己的URL映射方式,它是通过编辑项目url.py文件(myproject/url.py) 。 url.py文件看起来像 - from django.conf.urls import patterns, include, url from django.contrib import admin admin.au