美文网首页
springboot项目遇到的BUG

springboot项目遇到的BUG

作者: 靈08_1024 | 来源:发表于2018-01-01 23:14 被阅读469次

    1、在JPA插入时,前台误传ID,数据库若有ID,后台将变为修改。若无将是新增。
    2、日期类型接收:
    pom新增:

     <!--日期转换需要的jar-->
            <dependency>
                <groupId>com.fasterxml.jackson.datatype</groupId>
                <artifactId>jackson-datatype-jsr310</artifactId>
                <version>2.9.2</version>
            </dependency>
    

    yaml配置文件新增:

    #全局时间格式定义
    spring: 
       jackson:
           date-format: yyyy-MM-dd HH:mm:ss
    

    局部属性在实体类上使用@JSONFormat("yyyy-MM-dd")来指定日期格式。

    3、吐槽一个JPA里的问题:我一同事在JPA的repository里写了方法,未调用,然后上传。导致我处理了半天,注销了他的代码后,发现一下就好了。才发现这是随手写的一个方法,且没有@query。

    4、在结合redis存储时,报错如下(只截取了主要部分):

    java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.zz.lb.xx.cc.entity.vineVo.xxVo]
    

    报错大意为这个要存储到redis中的类需要序列化。

    5、全局日志的拦截:
    本全局日志从Spring4.1以后可以使用。其作用就是修改响应内容。

    package com.kindo.vine.filter;
    
    import com.kindo.vine.common.OperationContentLog;
    import com.kindo.vine.common.OperationLog;
    import com.kindo.vine.utils.JsonUtil;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.core.MethodParameter;
    import org.springframework.http.MediaType;
    import org.springframework.http.server.ServerHttpRequest;
    import org.springframework.http.server.ServerHttpResponse;
    import org.springframework.http.server.ServletServerHttpRequest;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Date;
    
    /**
     * Created by lingbao on 2017/11/20.
     *
     * @author lingbao
     * @Description
     * @Modify
     */
    @ControllerAdvice
    public class LogAdvice implements ResponseBodyAdvice {
    
        Logger logger = LoggerFactory.getLogger(LogAdvice.class);
    
        @Override
        public boolean supports(MethodParameter methodParameter, Class aClass) {
            //所有经过GetMapping的注解都不会进行日志记录
            if (null != methodParameter.getMethodAnnotation(GetMapping.class)) {
                return false;
            }
            return true;
        }
    
        @Override
        public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
    
            try {
    
                HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
    
                if (!RequestMethod.GET.toString().equals(request.getMethod())) {
    
                    String log = request.getParameter("log");
                    if (StringUtils.isNotBlank(log)) {
                        logger.info("记录日志:"+log);
                    } else
                        logger.error(request.getServletPath() + "日志为空!");
                }
            } catch (Exception e) {
                logger.error("记录日志错误", e);
            }
    
            return o;
        }
    }
    
    

    6、前后端分离远程调用:

    import com.kindo.vine.common.Constant;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.annotation.Order;
    import org.springframework.web.filter.OncePerRequestFilter;
    
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @Configuration
    @WebFilter
    public class CorsFilter extends OncePerRequestFilter {
    
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    
            response.addHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
            response.setHeader("Access-Control-Allow-Credentials","true");
            filterChain.doFilter(request, response);
        }
    }
    

    其中request.getHeader("Origin")动态获取远程请求的地址。

    redis错误:
    java.io.InvalidClassException是redis转换类错误。序列化错误!
    解决办法:
    在类中实现序列化,添加private static final long serialVersionUID = 5720718939199613394L;,然后清除redis缓存(flushall)。


    springboot+ElasticSearch5.6遇到的BUG:
    错误:availableProcessors is already set to [4], rejecting [4]
    解决:System.setProperty("es.set.netty.runtime.available.processors", "false");

        private Settings settings(){
            System.setProperty("es.set.netty.runtime.available.processors", "false");
            Settings settings = Settings.builder()
                    .put("cluster.name",clusterName)
                    .put("client.transport.sniff",true)
                    .build();
            client = new PreBuiltTransportClient(settings);
            return settings;
        }
    

    springboot 2.0.0.BUILD-SNAPSHOT版本:
    针对于实体,主键要有(strategy = GenerationType.IDENTITY)。否则会报错,测试数据库为MySQL。(报错内容为:Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.kindo.lily.entity.Medicine)

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
    

    JPA错误:
    自级联时,如果父节点ID为null,在保存时,会报错。
    错误内容:

     Data was not saved: object references an unsaved transient instance - save the transient instance before flushing
    

    解决:手动将父节点id为null的节点设置为null(setParent(null))。


    elasticsearch
    报错内容:NamedWriteable [org.elasticsearch.index.query.QueryBuilder][parent_id] is already registered for...
    诊断:缺少Jar包。
    解决:

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.6.0</version>
    </dependency>
    
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>transport</artifactId>
                <version>5.6.0</version>
            </dependency>
    

    2.0.0.BUILD-SNAPSHOT版本中,因为当初版本仓库不稳定,所以出现启动错误(错误已经不能复原了,大意是netty4 transport error)。导致启动失败。折腾了很久很久,最后研究出来了。所以不稳定的版本少用!!!!

            <dependency>
                <groupId>org.elasticsearch</groupId>
                <artifactId>elasticsearch</artifactId>
                <version>5.6.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>transport</artifactId>
                <version>5.6.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.elasticsearch.plugin</groupId>
                        <artifactId>transport-netty4-client</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <dependency>
                <groupId>org.elasticsearch.plugin</groupId>
                <artifactId>transport-netty4-client</artifactId>
                <version>5.5.3</version>
            </dependency>
    

    boot版本是2.0.0:注入一个@FeignClient 的调用客户端,报错说为null注入失败。最后发现是swagger的版本太低,调至2.6.1了(2.5.x以上)。


    错误内容:Cannot create binder factory, noMETA-INF/spring.bindersresources found on the classpath
    修复:没有rabbitmq。添加依赖:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    </dependency>
    

    配置:

    spring: 
        rabbitmq: #RabbitMQ相关的配置
            host: localhost
            port: 5672
            username: guest
            password: guest
    

    其中rabbitmq的java端口就是5672,而web端口为15672。使用自带用户名。


    在配置cloud时,尽量不要使用{}之类的来表示某个配置信息,如{server.port},会出现There is no known eureka server; cluster server list is empty错误。
    解决:写上具体的值就好了。


    Tomcat启动地址冲突:(来自慕课网,未验证)

    搜索8080端口的进程,最后一列为pid

    netstat -aon|findstr ":8080"

    杀掉pid为1234的进程

    taskkill /F /pid 1234

    以下为本文所参考的地址:

    全局日志拦截参考地址:http://blog.csdn.net/u012852374/article/details/53837156

    相关文章

      网友评论

          本文标题:springboot项目遇到的BUG

          本文链接:https://www.haomeiwen.com/subject/sgfqmxtx.html