Tag Archives: spring

Springcloud Project Error: web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error

Question

In the springcloud project, the consumer module uses resttemplate to call the provider module. When accessing a method in the consumer module, the following error occurs:

org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error
	at org.springframework.web.client.HttpServerErrorException.create(HttpServerErrorException.java:79) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:785) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:743) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]

Solution:

When I first saw the error of 500, I naturally thought it was the problem of background service. However, the log information in the consumer module was relatively general, so it was difficult to locate the problem. After checking, it was found that an error occurred when the consumer used resttemplate to call the provider service , so check the log of the provider module, and sure enough, more detailed error information was found:

java.lang.IllegalArgumentException: Parameter value [2021-10-25] did not match expected type [java.util.Date (n/a)]

Then the problem will be solved

Idea error: (4, 28) Java: package com.alibaba.fastjson does not exist

The package has been imported through Maven in DEA, and the location of the package can also be located in idea, but error is always reported when compiling, and the package cannot be found.

Presumably, the reason is that the version of idea is incompatible with the build built by Maven

It is recommended to uninstall the idea and install it with another version of the idea. If you do not want to replace the idea, you can take the following measures.

The solution is as follows:

Hosting the build and run of idea under maven

When checked, recompilation can run normally

Springmvc response. Senderror() custom message prompt

When the HTTP request is abnormal, spring MVC only returns the error code by default, but the error message is ignored

The message field is empty. If you want to get detailed information, you can add the following configuration in the configuration file:

server:
  error:
    include-message: always

After adding, the response body is:

Fastjson Error: Error: Cannot create inner bean ‘org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

Error: Cannot create inner bean ‘org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#0

The spring-mvc.xml configuration file is written like this

 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                 <property name="objectMapper">
                     <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                         <property name="failOnEmptyBeans" value="false"/>
                     </bean>
                 </property>
             </bean>

reason:

Only the fastjosn dependency is imported, and the following dependency is not imported

 <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
             <version>2.12.4</version>
         </dependency>

These three jar packages are missing from the generated package

jackson-annotations-2.12.4.jar jackson-databind-2.12.4.jar jackson-core-2.12.4.jar

The problem is solved after importing dependencies.

[Solved] WebFlux Error: DataBufferLimitException: Part headers exceeded the memory usage limit of 8192 bytes

Question:

An error occurs when Webflux uploads a file:

14:32:24.628 [61667d78915db10adaa025b4da32871f/daa025b4da32871f] [reactor-http-epoll-4] ERROR o.s.w.s.a.HttpWebHandlerAdapter - [7161d1a8-33] 500 Server Error for HTTP POST "/api/XXXXX/XXXXX"
org.springframework.core.io.buffer.DataBufferLimitException: Part headers exceeded the memory usage limit of 8192 bytes
        at org.springframework.http.codec.multipart.MultipartParser$HeadersState.onNext(MultipartParser.java:360)
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
        |_ checkpoint ⇢ org.springframework.security.web.server.authentication.logout.LogoutWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.savedrequest.ServerRequestCacheWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.authentication.AuthenticationWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.authentication.AuthenticationWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.context.ReactorContextWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.header.HttpHeaderWriterWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.config.web.server.ServerHttpSecurity$ServerWebExchangeReactorContextWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.security.web.server.WebFilterChainProxy [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.cloud.sleuth.instrument.web.TraceWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
        |_ checkpoint ⇢ HTTP POST "/api/iot/notice/add" [ExceptionHandlingWebHandler]
Stack trace:
                at org.springframework.http.codec.multipart.MultipartParser$HeadersState.onNext(MultipartParser.java:360)
                at org.springframework.http.codec.multipart.MultipartParser.hookOnNext(MultipartParser.java:104)
                at org.springframework.http.codec.multipart.MultipartParser.hookOnNext(MultipartParser.java:46)
                at reactor.core.publisher.BaseSubscriber.onNext(BaseSubscriber.java:160)
                at org.springframework.cloud.sleuth.instrument.reactor.ScopePassingSpanSubscriber.onNext(ScopePassingSpanSubscriber.java:90)
                at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:120)
                at org.springframework.cloud.sleuth.instrument.reactor.ScopePassingSpanSubscriber.onNext(ScopePassingSpanSubscriber.java:90)
                at reactor.core.publisher.FluxPeek$PeekSubscriber.onNext(FluxPeek.java:199)
                at org.springframework.cloud.sleuth.instrument.reactor.ScopePassingSpanSubscriber.onNext(ScopePassingSpanSubscriber.java:90)
                at reactor.core.publisher.FluxMap$MapSubscriber.onNext(FluxMap.java:120)
                at reactor.netty.channel.FluxReceive.drainReceiver(FluxReceive.java:265)
                at reactor.netty.channel.FluxReceive.onInboundNext(FluxReceive.java:371)
                at reactor.netty.channel.ChannelOperations.onInboundNext(ChannelOperations.java:381)
                at reactor.netty.http.server.HttpServerOperations.onInboundNext(HttpServerOperations.java:535)
                at reactor.netty.channel.ChannelOperationsHandler.channelRead(ChannelOperationsHandler.java:94)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
                at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
                at reactor.netty.http.server.HttpTrafficHandler.channelRead(HttpTrafficHandler.java:252)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
                at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
                at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)
                at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324)
                at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:311)
                at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:432)
                at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
                at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
                at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
                at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
                at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
                at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795)
                at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe$1.run(AbstractEpollChannel.java:388)
                at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
                at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
                at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:384)
                at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
                at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
                at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
                at java.lang.Thread.run(Thread.java:882)

reason:

You can only upload files with a maximum size of 8KB, which exceeds the limit and cannot be uploaded normally

Solution:

Method I (not effective):

Direct setting    max-in-memory-size   It can take effect

spring:
  codec:
    max-in-memory-size: 100MB

However, the above code does not take effect in the spring 2.X.x version. The official said it was solved. It is estimated that it was solved in the later version, but the project has been produced. It is certainly impossible to change the version now, so we have to find another way. During his startup, debug found that it was set to 262144 when initializing the code:

Method II:

Configure configuration. In the configuration class of webfluxconfigurer in implements, implement configurehttpmessagecodes for configuration. The example is as follows


import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader;
import org.springframework.http.codec.multipart.MultipartHttpMessageReader;
import org.springframework.web.reactive.config.WebFluxConfigurer;

@Configuration
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        DefaultPartHttpMessageReader partReader = new DefaultPartHttpMessageReader();
        // 9 KiB, default is 8 KiB
        partReader.setMaxHeadersSize(100*1024*1024);
        partReader.setEnableLoggingRequestDetails(true);

        MultipartHttpMessageReader multipartReader = new MultipartHttpMessageReader(partReader);
        multipartReader.setEnableLoggingRequestDetails(true);

        configurer.defaultCodecs().multipartReader(multipartReader);

    }
}

Done!

[Solved] Spring Cloud Use Ribbon Error: No instances available for XXX

Question

After configuring load balancing, start springboot and report an error

reason

The version difference of jar
I first used ribbon and Eureka. When I added them, I didn’t notice that the following two versions were abandoned

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

Solution:

The dependency of replacing the Eureka registry module is

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>3.0.4</version>
        </dependency>

The dependency of replacing the service provider and consumer modules is
the ribbon required by the consumer module has been built-in compatible with the latest version of Eureka

         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>3.0.4</version>
        </dependency>

[Solved] SpringMVC Error: element web-app must be declared

Problem background

Today, when learning spring MVC, you need to configure the web.xml file, and an error message element web app must be declared appears.

 

Solution:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
</web-app>

After asynchronous file import and springboot multipartfile upload, the @async asynchronous processing reports an error: nosuchfileexception

First question

When there is a large amount of data in Excel, the process of Java background parsing may take a long time, but users do not need to wait. At this time, consider the asynchronous import of files

There are several ways to implement the file asynchronous method. Here, it is implemented by specifying the asynchronous thread pool, that is, @ async (“thread pool name”) annotates the asynchronous method.

However, after testing, it is found that the annotations of this annotation are also annotated, but the asynchronous effect cannot be realized.

After several twists and turns, it is found that asynchronous methods can call non asynchronous methods, which can achieve asynchronous effect; First, non asynchronous methods call asynchronous methods, which will fail. What is said here is in the same Java class.

In different Java classes, the above problems do not exist

The second problem
uses the asynchronous method to receive files through the controller and process them in the service layer. At this time, the controller has returned the results of successful execution. The rest is to analyze and store them in the service layer. Unexpectedly, an error is reported in the service

java.nio.file.NoSuchFileException: D:\UserData\Temp\undertow.1407321862395783323.8400\undertow4517937229384702645upload

Methods in controller

@PostMapping("/test")
public R<String> test(MultipartFile file) {
	testService.test(file);
	return R.success("successful to import");
}

Methods in service

@Async("asyncImportExecutor")
public void test(MultipartFile file) {
    try {
        EasyExcelUtil.read(file.getInputStream(), Test.class, this::executeImport)
                    .sheet().doRead();
    } catch (Exception ex) {
        log.error("[test]Asynchronous import exceptions:", ex);
    }
}

When I saw this exception nosuchfileexception, I was stunned. The test was conducted through postman, so I began to suspect the problem of postman. After troubleshooting, there was no problem with postman and path, and the asynchronous call process was OK

Then think of the abnormal prompt, that is, the file can not be found. According to the printed log, it can’t be found locally. Then there was the following writing

Methods in controller

@PostMapping("/test")
public R<String> test(MultipartFile file) {
	try {
		testService.test(file.getInputStream());
	} catch (IOException e) {
		log.error("[test]Exception log:", e);
		return R.fail("Import failed");
	}
	return R.success("Import successful");
}

Methods in service

@Async("asyncImportExecutor")
public void test(InputStream file) {
    try {
        EasyExcelUtil.read(file, Test.class, this::executeImport)
                    .sheet().doRead();
    } catch (Exception ex) {
        log.error("[test]Asynchronous import exceptions:", ex);
    }
}

So you don’t report mistakes
later, I debugged and found that the temporary file was generated by the multipartfile object in the controller layer. I had been writing the synchronization method, and I didn’t notice that the multipartfile object would generate a temporary file. Later, it was found that after the result returned in the controller, there was no temporary file.

Error summary:
because the asynchronous method is used, there will be a main thread and an asynchronous thread. After uploading a file, an instance of multipartfile type will be formed and a temporary file will be generated. At this time, it is in the main thread. After the instance of multipartfile is handed over to the asynchronous thread for processing, the temporary file will be destroyed by springboot (spring). The above exception will appear when you go to getinputstream in the asynchronous thread.

The following method is to take the InputStream stream as the input parameter, so the file cannot be found.

Error pathvariable annotation was empty on param 0 when migrating idea to eclipse

Recently, a project was developed with idea + maven, and it has been running without problem. Because idea takes up too much memory, I want to debug a problem on eclipse. I found the following errors when I start Eclipse:

Caused by: java.lang.IllegalStateException: PathVariable annotation was empty on param 0.
	at feign.Util.checkState(Util.java:129)
	at org.springframework.cloud.openfeign.annotation.PathVariableParameterProcessor.processArgument(PathVariableParameterProcessor.java:51)
	at org.springframework.cloud.openfeign.support.SpringMvcContract.processAnnotationsOnParameter(SpringMvcContract.java:299)
	at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:111)
	at org.springframework.cloud.openfeign.support.SpringMvcContract.parseAndValidateMetadata(SpringMvcContract.java:194)
	at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:62)

Obviously, it is because the feignclient Parameter annotation does not display the specified value. The source code is as follows:

    @GetMapping("projects/{projectId}/models")
    Result<RSCPage<Model>> list(@PathVariable String projectId, @RequestParam Integer current,
                                @RequestParam Integer pageSize, @RequestParam(required = false) String name,
                                @RequestParam(required = false) Integer relationship, @RequestParam(required = false) String sorter);

There are similar hosts in spring MVC, but no errors are reported.

Generally, it is customary not to specify value when writing spring MVC parameter annotations, such as requestparam/pathvariable. Since the project has been running for some time, code level problems can be eliminated.

According to the spring naming mechanism, if the specified value is not displayed,   Both spring MVC and spring faign use the same parameternamediscoverer   Defaultparameternamediscoverer   To find the parameter name. It attempts to find the parameter name using the following steps:

First, it uses the standardreflectionparameternamediscovery to try to find the variable name with reflection. This is only possible when compiling classes with – parameters. Second, if it fails, use localvariabletableparameternamediscovery. It tries to find the variable name from the debugging information in the ASM library class file. However, the javac compiler ignores the debugging information of parameter names in the java interface class file. The difference between spring MVC and faign appears here. Feign is the annotation added on the interface, while spiring MVC is the annotation added on the implementation class. This is why feign cannot find the parameter name without – parameter.

Solution: open the eclipse configuration window window & gt; Preference, expand Java & gt; Compiler, check the option in the red box below and recompile

  If you compile manually, you can add the javac parameter – G – parameter parameter
idea and Maven take these parameters by default, so you don’t need to configure them manually