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

HTTP错误502.3-在azure tomcat应用程序服务中部署Spring boot应用程序后,网关错误

桂德义
2023-03-14

我在azure tomcat应用程序服务中部署了spring boot Rest应用程序。这里,我使用FTP将应用程序从本地tomcat webapps文件夹复制到azure tomcat webapps fodler(复制的是应用程序文件夹结构,而不是war文件)。

它工作得很好。但一段时间后,服务器没有响应并返回HTTP错误502.3-坏网关

剩下的所有具有URI-myapp/ssp/***返回状态代码502.3的请求

当我重新启动应用程序服务时,一切都在工作,但过了一段时间后,问题又出现了。

我怀疑我的AuthenticationFilter.java&RequestValidator有问题。java&ControllerAdvice文件

/**
 * @param args
 */
public static void main( String[ ] args ) {

    SpringApplication sspSpringBootApplciation = new SpringApplication( SSPApplication.class );
    sspSpringBootApplciation.addListeners( new ApplicationPidFileWriter( ) );
    sspSpringBootApplciation.run( args );
}

/**
 * @return
 */
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurerAdapter( ) {

    return new ApplicationSecurity( );
}

@Bean
public String telemetryConfig( ) {

    String telemetryKey = "zzzz";
    if( telemetryKey != null ){
        TelemetryConfiguration.getActive( ).setInstrumentationKey( telemetryKey );
    }
    return telemetryKey;
}

@Bean
public FilterRegistrationBean aiFilterRegistration( ) {

    FilterRegistrationBean registration = new FilterRegistrationBean( );
    registration.setFilter( webRequestTrackingFilter( ) );
    registration.addUrlPatterns( "/*" );
    registration.setOrder( 1 );
    return registration;
}

@Bean( name = "WebRequestTrackingFilter" )
public Filter webRequestTrackingFilter( ) {

    return new WebRequestTrackingFilter( );
}

@Bean
public ErrorPageFilter errorPageFilter( ) {

    return new ErrorPageFilter( );
}

@Bean
public FilterRegistrationBean disableSpringBootErrorFilter( ErrorPageFilter filter ) {

    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean( );
    filterRegistrationBean.setFilter( filter );
    filterRegistrationBean.setEnabled( false );
    return filterRegistrationBean;
}

`@ControllerAdvice公共类RestEntityExceptionHandler扩展ResponseEntityExceptionHandler{

@Autowired
private Environment environment;

private SSPLogger logger = new SSPLogger( getClass( ) );

/**
 * @return
 */
private String getEnvironment( ) {

    String[ ] activeProfiles = environment.getActiveProfiles( );
    if( activeProfiles != null && activeProfiles.length > 1 ){
        return SSPEnvironment.getEnvironment( activeProfiles[ 0 ] ).name( );
    }
    return SSPEnvironment.UNKNOWN.name( );

}

/**
 * @param errorCode
 * @return
 */
private HttpStatus getHttpstatusCode( String errorCode ) {

    try{
        return HttpStatus.valueOf( Integer.parseInt( errorCode ) );
    } catch ( Exception e ){

        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}

/**
 * @param ex
 * @return
 */
@ExceptionHandler( {    .class , IllegalStateException.class , SSPRestException.class ,
        Exception.class } )
@ResponseBody
ResponseEntity< Object > handleControllerException( Exception ex ) {

    HttpHeaders headers = new HttpHeaders( );
    headers.setContentType( MediaType.APPLICATION_JSON );
    ex.printStackTrace( );
    if( ex instanceof SSPRestException ){
        SSPRestException exp = ( SSPRestException ) ex;
        CustomErrorResponse customErrorResponse = new CustomErrorResponse( );
        customErrorResponse.setStatusCode( exp.getErrorCode( ) );
        customErrorResponse.setErrorMessage( exp.getErrorMessage( ) );
        customErrorResponse.setErrorDescription( exp.getErrorDescription( ) );
        customErrorResponse.setErrorKey( exp.getErrorKey( ) );
        customErrorResponse.setEnvironment( getEnvironment( ) );
        logger.logException( LogLevel.ERROR , customErrorResponse );

        HttpStatus httpstatusCode = getHttpstatusCode( exp.getErrorCode( ) );

        return new ResponseEntity<>( customErrorResponse , headers , httpstatusCode );
    }
    if( ex instanceof HttpRequestMethodNotSupportedException ){
        String statusCode = "405";
        headers.setContentType( MediaType.APPLICATION_JSON );
        CustomErrorResponse customErrorResponse = new CustomErrorResponse( );
        customErrorResponse.setStatusCode( statusCode );
        customErrorResponse.setErrorMessage( ex.getMessage( ) );
        customErrorResponse.setErrorKey( "" );
        customErrorResponse.setEnvironment( getEnvironment( ) );
        HttpStatus httpstatusCode = getHttpstatusCode( statusCode );
        return new ResponseEntity<>( customErrorResponse , headers , httpstatusCode );
    } else{
        String statusCode = "UNKNOWN";
        CustomErrorResponse customErrorResponse = new CustomErrorResponse( );
        customErrorResponse.setStatusCode( statusCode );
        customErrorResponse.setErrorMessage( ex.getMessage( ) );
        if( ex.getCause( ) != null ){
            customErrorResponse.setErrorDescription( ex.getCause( ).getMessage( ) );
        }
        customErrorResponse.setErrorKey( "UNAHNDLED_EXCEPTION" );
        customErrorResponse.setEnvironment( getEnvironment( ) );
        HttpStatus httpstatusCode = getHttpstatusCode( statusCode );
        logger.logException( LogLevel.ERROR , customErrorResponse );
        return new ResponseEntity<>( customErrorResponse , headers , httpstatusCode );
    }
}

}````@order(SecurityProperties.access_override_order)公共类ApplicationSecurity扩展WebSecurityConfigurerAdapter{

    @Override
    protected void configure( HttpSecurity http ) throws Exception {

    http.csrf( ).disable( ).sessionManagement( ).sessionCreationPolicy( SessionCreationPolicy.STATELESS );
    http.authorizeRequests( ).antMatchers( "/spp/**" ).addFilterBefore( new AuthenticationFilter( ) , SecurityContextPersistenceFilter.class );
http.authorizeRequests( ).antMatchers( "/healthcheck/**" , "/unoauth/**" ).permitAll( ).antMatchers( HttpMethod.OPTIONS , "/**" ).permitAll( );

```

@Autowired
private AppConstants appConstants;

@Autowired
private CacheTemplate cacheTemplate;

@Autowired
private RestClient restClient;

/*
 * (non-Javadoc)
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
 * afterCompletion(javax.servlet.http.HttpServletRequest,
 * javax.servlet.http.HttpServletResponse, java.lang.Object,
 * java.lang.Exception)
 */
@Override
public void afterCompletion( HttpServletRequest request , HttpServletResponse response , Object object ,
                Exception arg3 ) throws Exception {

}

/**
 * @param cookies
 * @return
 */
private String getGsidFromRequest( Cookie[ ] cookies ) {

    String gsid = null;
    if( cookies != null ){
        Cookie gsidCookie = Arrays.stream( cookies ).filter( x-> x.getName( ).equals( "gsid" ) ).findFirst( )
                        .orElse( null );
        if( gsidCookie != null ){
            gsid = gsidCookie.getValue( );
        }
        if( Utils.isEmpty( gsid ) ){
            throw new SSPRestException( ErrorCode.InvalidRequest , "gsid is missing" , getClass( ) );
        }
    }
    return gsid;
}

/**
 * @return
 */
private UserCashedInfo getTempUserInfo( ) {

    UserCashedInfo cashedInfo = new UserCashedInfo( );
    cashedInfo.setEmailId( "sssssss" );
    cashedInfo.setUserId( 1 );
    cashedInfo.setUserRole( 1 );
    cashedInfo.setRefreshToken( "" );
    cashedInfo.setCaseInstanceId( 1 );
    cashedInfo.setUserName( "Test User" );
    return cashedInfo;
}

/**
 * @param accessToken
 * @return
 */
private boolean isRequestHadAccessToken( String accessToken ) {

    if( Utils.isEmpty( accessToken ) ){
        throw new SSPRestException( ErrorCode.InvalidRequest , "Access Token is Mandatory" , getClass( ) );
    }
    return true;
}

/*
 * (non-Javadoc)
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
 * postHandle(javax.servlet.http.HttpServletRequest,
 * javax.servlet.http.HttpServletResponse, java.lang.Object,
 * org.springframework.web.servlet.ModelAndView)
 */
@Override
public void postHandle( HttpServletRequest request , HttpServletResponse response , Object object ,
                ModelAndView model ) throws Exception {

}

/*
 * (non-Javadoc)
 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
 * preHandle(javax.servlet.http.HttpServletRequest,
 * javax.servlet.http.HttpServletResponse, java.lang.Object)
 */
@Override
public boolean preHandle( HttpServletRequest request , HttpServletResponse response , Object object )
                throws Exception {

    boolean isValidRequest = false;

    String isOauthRequiredParam = request.getParameter( "isOauth" );

    String methodName = request.getMethod( );
    if( methodName != null && methodName.equalsIgnoreCase( "OPTIONS" ) ){
        isValidRequest = true;
    }

    if( !isValidRequest ){
        if( !Utils.isEmpty( isOauthRequiredParam ) && isOauthRequiredParam.equals( "false" ) ){
            isValidRequest = true;
            UserCashedInfo cashedInfo = getTempUserInfo( );
            Utils.updateUserLocalThread( cashedInfo );
        } else{
            String accessToken = request.getHeader( "oauth" );
            boolean isRequestHadAccessToken = isRequestHadAccessToken( accessToken );
            String gsid = getGsidFromRequest( request.getCookies( ) );
            if( isRequestHadAccessToken && !Utils.isEmpty( gsid ) ){
                UserCashedInfo cashedInfo = cacheTemplate.getItem( gsid );
                if( cashedInfo != null ){
                    String userEmail = validateAccessToken( accessToken );
                    if( userEmail != null && userEmail.equals( cashedInfo.getEmailId( ) ) ){
                        Utils.updateUserLocalThread( cashedInfo );
                        isValidRequest = true;
                    } else{
                        throw new SSPRestException( ErrorCode.UnAuthenticateUser , "" , getClass( ) );
                    }

                } else{
                    throw new SSPRestException( ErrorCode.UnAuthenticateUser , "" , getClass( ) );
                }
            } else{
                throw new SSPRestException( ErrorCode.GsidMissing , "" , getClass( ) );
            }
        }
    }
    return isValidRequest;
}

/**
 * @param accessToken
 * @return
 */
private String validateAccessToken( String accessToken ) {

    CustomeJsonResponse validateResponse = restClient.ValidateAcessToken( accessToken );
    if( validateResponse.getStatusCode( ) == 200 ){
        return ( ( ValidateAcessTokenResponse ) validateResponse.getData( ) ).getAccess_token( )
                        .get( appConstants.getUserEmail( ) );
    } else{
        throw new SSPRestException( ErrorCode.ApValidateAccessTokenError , "" , getClass( ) );
    }
}
private SSPLogger logger = new SSPLogger( getClass( ) );

@Override
public void destroy( ) {

}

/*
 * (non-Javadoc)
 * @see com.xxx.ssp.security.GenericFilter#doFilter(javax.servlet.
 * ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter( ServletRequest req , ServletResponse res , FilterChain chain )
                throws IOException , ServletException {

    HttpServletRequest request = ( HttpServletRequest ) req;

    String accessToken = request.getHeader( "oauth" );
    boolean isValidRequest = false;
    String isOauthRequiredParam = request.getParameter( "isOauth" );
    String methodName = request.getMethod( );
    if( methodName != null && methodName.equalsIgnoreCase( "OPTIONS" ) ){
        isValidRequest = true;
    } else{
        if( !Utils.isEmpty( isOauthRequiredParam ) && isOauthRequiredParam.equals( "false" ) ){
            isValidRequest = true;
        } else{
            logger.debug( "Requeste validation required : true" );

            boolean isRequestHadAccessToken = isRequestHadAccessToken( accessToken );
            String gsid = getGsidFromRequest( request.getCookies( ) );

            if( isRequestHadAccessToken && !Utils.isEmpty( gsid ) ){
                isValidRequest = true;
            } else{
                throw new SSPRestException( ErrorCode.InternalServerError ,
                                " Access Token or GSID is mssing in the request" , getClass( ) );
            }
        }
    }
    if( isValidRequest ){
        chain.doFilter( req , res );
    } else{
        throw new SSPRestException( ErrorCode.UnauthorisedRequest , "Invalid User" , getClass( ) );
    }
}

/**
 * @param cookies
 * @return
 */
private String getGsidFromRequest( Cookie[ ] cookies ) {

    String gsid = null;
    if( cookies != null ){
        Cookie gsidCookie = Arrays.stream( cookies ).filter( x-> x.getName( ).equals( "gsid" ) ).findFirst( )
                        .orElse( null );
        if( gsidCookie != null ){
            gsid = gsidCookie.getValue( );
        }
        if( Utils.isEmpty( gsid ) ){
            throw new SSPRestException( ErrorCode.UnAuthenticateUser , "gsid is missing" , getClass( ) );
        }
    }
    return gsid;
}

/*
 * (non-Javadoc)
 * @see
 * com.xxx.ssp.security.GenericFilter#init(javax.servlet.FilterConfig)
 */
@Override
public void init( FilterConfig arg0 ) throws ServletException {

}

/**
 * @param accessToken
 * @return
 */
private boolean isRequestHadAccessToken( String accessToken ) {

    if( Utils.isEmpty( accessToken ) ){
        throw new SSPRestException( ErrorCode.UnAuthenticateUser , "Access Token is Mandatory" , getClass( ) );
    }
    return true;
}

`@组件公共类SSPCORSFilter实现筛选器{

private SSPLogger sSPLogger = null;

public SSPCORSFilter( ){

    sSPLogger = new SSPLogger( getClass( ) );
    sSPLogger.info( "CORSFilter initialized" );
}

@Override
public void destroy( ) {

}

@Override
public void doFilter( ServletRequest req , ServletResponse res , FilterChain chain )
                throws IOException , ServletException {

    String origin = ( ( HttpServletRequest ) req ).getHeader( "Origin" );
    sSPLogger.info( "CORSFilter Request origin : " + origin );
    HttpServletResponse response = ( HttpServletResponse ) res;
    response.setHeader( "Access-Control-Allow-Origin" , origin );
    response.setHeader( "Access-Control-Allow-Credentials" , "true" );
    response.setHeader( "Access-Control-Allow-Methods" , "GET, POST, PUT, DELETE, OPTIONS" );
    // response.setHeader( "Access-Control-Allow-Headers" , "Content-Type,
    // Accept, X-Requested-With, oauth" );
    response.setHeader( "Access-Control-Request-Headers" ,
                    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, oauth, access-control-allow-credentials" );
    response.setHeader( "Access-Control-Allow-Headers" ,
                    "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, oauth, access-control-allow-credentials" );

    chain.doFilter( req , res );
}

@Override
public void init( FilterConfig filterConfig ) {

}

}`

共有1个答案

孔山
2023-03-14

我在查看线程转储后修复了这个问题。根本原因是db连接池出现死锁。所以我的请求没有得到数据库连接..超时后,IIS服务器返回状态为“http-error-502-3-bad-gateway”的请求

 类似资料:
  • 我正在Heroku上部署一个网站,但我在尝试运行“Heroku open”时收到了“应用程序错误”。 我相信我已经成功地将文件推送到Heroku中,这是我的“git推送heroku master”代码的一部分: 当我运行“heroku config-s | grep PATH”时,我得到了 我正在使用Ruby 1.9.3和Rails 4.0.0 文件夹 宝石环境 箱/轨道 垃圾箱/包裹 仓/耙

  • 完成干净的构建后,我将war文件复制到Tomcat的文件夹中。但是部署会发生两次,并且在上下文已经存在的情况下以异常结束。我错过了什么? 非常感谢您的帮助。

  • 我的应用程序https://github.com/amyequinn/weatherapp在终端运行npm启动时运行得很好,但是当将应用程序部署到Heroku时,它崩溃了,我找不到解决方案。错误为H10,应用程序在Get方法时崩溃,状态503.... “2020-05-08T23:13:34.132652+00:00 Heroku[router]:at=error code=h10 desc=”A

  • 我有一个spring-boot项目在IntelliJ IDE中运行良好,我试图将其部署在Heroku服务器上。该项目部署成功,但当我试图从POSTMAN访问它时,我得到了503错误:服务不可用。 以下是从Heroku成功部署后的日志记录: Heroku的申请日志: 有人能帮帮我吗?提前谢了。

  • 我在服务器上运行应用程序时出错,它在本地正常工作,我只需输入Run(npm start)并在本地正常运行。但和我在服务器上做的一样,我得到了下面给出的错误。请有人帮帮我。 {“name”:“chakde11”,“version”:“1.0.0”,“private”:false,“homepage”:http://chakde11.com/“,”依赖项“{bootstrap:“4.1.1”,“cha

  • 我有一个错误应用程序在我的本地电脑上工作,但当我把它发送给heroku时,它崩溃了。错误日志给出错误H10&表示: 编辑: 有没有人以前有过这种情况,并且知道是什么导致了这个问题?我找不到解决办法。 多谢了。