Exception
一.jar包冲突
1.问题描述:
2.问题分析:
上面的两个slf4j jar包冲突了
3.问题解决
我们只要在pom.xml
排除以上两个中的一个jar包即可:
<dependencies>
<dependency>
<groupId>com.changgou</groupId>
<artifactId>changgou_service_goods_api</artifactId>
<version>1.0-SNAPSHOT</version>
<!--排除这个slf4j-log4j12,不然会有jar包冲突-->
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
二.JDK使用9版本引发的问题
1.问题描述:
2.问题分析:
因为JAXB-API是java ee的一部分,在jdk9中没有在默认的类路径中;
java ee api在jdk中还是存在的,默认没有加载而已,jdk9中引入了模块的概念,可以使用
模块命令--add-modules java.xml.bind
引入jaxb-api;
3.问题解决
1.把idea中JDK版本改为8
2.加入如下依赖:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
三.六.springcloud集成feign进行远程调用时出现@FeignClient同名问题
1.问题描述:
2019-08-15 15:01:35.652 ERROR 11744 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'content.FeignClientSpecification', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
2.问题分析:
升级Spring Boot 2.1.0 Spring Cloud Greenwich.M1 版本后,在2个Feign接口类内定义相同的名字, @FeignClient(name = 相同的名字 就会出现报错,在之前的版本不会提示报错.
这是说Feign的注册,有同名的feign的名字重复注册。
其实报错时,idea已经给出了解决问题的方法:
3.问题解决:
①最有效:
在application.yml配置文件的spring配置中加上:
spring.main.allow-bean-definition-overriding=true
②也行:
解决办法就是将Feign调用,相同的name也就是跨服务调用,同一个服务的接口,不要分散的写在多个接口类中,而是放到同一个接口类中定义调用。
③临时解决:(适用于只有一个feign调用)
两个feign中改成不同的名字
四. ElasticsearchRepository<SkuInfo,Long>中pojo类型填写错误
1.问题描述:
Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.changgou.goods.pojo.Sku
2.问题分析:
代码中用的是ElasticsearchRepository<Sku,Long>
而调用skuEsMapper.saveAll(skuInfos);时传入的是SkuInfo类型
SkuInfo:(ES类型)
@Document(indexName = "skuinfo", type = "docs")
public class SkuInfo implements Serializable {
//商品id,同时也是商品编号
@Id
private Long id;
//SKU名称
@Field(type = FieldType.Text, analyzer = "ik_smart")
private String name;
//商品价格,单位为:元
@Field(type = FieldType.Double)
private Long price;
//库存数量
private Integer num;
//商品图片
private String image;
//商品状态,1-正常,2-下架,3-删除
private String status;
//创建时间
private Date createTime;
//更新时间
private Date updateTime;
//是否默认
private String isDefault;
//SPUID
private Long spuId;
//类目ID
private Long categoryId;
//类目名称
@Field(type = FieldType.Keyword)
private String categoryName;
//品牌名称
@Field(type = FieldType.Keyword)
private String brandName;
Sku:(普通pojo)
@ApiModel(description = "Sku",value = "Sku")
@Table(name="tb_sku")
public class Sku implements Serializable{
@ApiModelProperty(value = "商品id",required = false)
@Id
@Column(name = "id")
@JsonSerialize(using = ToStringSerializer.class)
private Long id;//商品id
@ApiModelProperty(value = "商品条码",required = false)
@Column(name = "sn")
private String sn;//商品条码
@ApiModelProperty(value = "SKU名称",required = false)
@Column(name = "name")
private String name;//SKU名称
@ApiModelProperty(value = "价格(分)",required = false)
@Column(name = "price")
private Integer price;//价格(分)
@ApiModelProperty(value = "库存数量",required = false)
@Column(name = "num")
private Integer num;//库存数量
...
3.问题解决:
改成:
五.springcloud集成feign进行远程调用问题@FeignClient(name=“xxx”)问题:
1.问题描述
com.netflix.hystrix.exception.HystrixRuntimeException: SkuFeign#getByStatus(String) failed and no fallback available.
...
Caused by: java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: sku
...
Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: sku
...
at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:112)
at org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:83)
... 32 more
2.问题分析
主要原因分析:
Caused by: java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: sku
这里@FeignClient(name=“sku”)中的name="sku"出错,eureka中没有sku这个客户端
@FeignClient(name=“xxx”)或者@FeignClient(value=“xxx”)中的name或者value应是已经注册到注册中心的客户端
3.问题解决
六.springcloud集成feign进行远程调用读取数据库数据存到Elasticsearch时遇到超时问题:
1.问题描述
com.netflix.hystrix.exception.HystrixRuntimeException: SkuFeign#getByStatus(String) failed and no fallback available.
...
Caused by: feign.RetryableException: Read timed out executing GET http://goods/sku/findByStatus/1
...
Caused by: java.net.SocketTimeoutException: Read timed out
...
2.问题分析
主要原因:
Caused by: java.net.SocketTimeoutException: Read timed out
Feign本身集成了Ribbon依赖和自动配置,因此不需要额外引入依赖,也不需要再注入RestTemplate对
象。Feign内置的ribbon默认设置了请求超时时长,默认是1000ms,可以修改ribbon内部有重试机
制,一旦超时,会自动重新发起请求。如果不希望重试可以关闭配置。
这里springcloud的feign中内置的负载均衡ribbon默认超时时长过短,而在进行查询数据库存到es中时,如果数据库中数据量特别多,此时单单查询数据库信息时间都要消耗5、6秒,而默认时间只有1秒,就会造成超时异常。
3.问题解决
在我们配置application.yml配置时,可以不使用默认的ribbon配置,重新配置ribbon的超时时间等:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 配置为随机
ConnectTimeout: 1000 # 指的是建立连接所用的时间
ReadTimeout: 2000 # 指的是建立连接后从服务器读取到可用资源所用的时间
MaxAutoRetries: 0 # 最大重试次数(第一个服务)
MaxAutoRetriesNextServer: 0 # 最大重试下一个服务次数(集群的情况才会用到)
OkToRetryOnAllOperations: false # 是否对所有的请求都重试
实际项目中,进行如下配置问题已解决:
七.使用JSON.parseArray()格式化String类型为list类型时报错
1.问题描述:
com.alibaba.fastjson.JSONException: syntax error, expect {, actual error, pos 1, fastjson-version 1.
2.问题分析:
正确的JSON格式为:
{
名称1:值1,
名称2:值2
}
而在把一个MAP类型存入到redis中的时候,在Map中使用“=”连接键值
就算把Map.toString()存入到redis中的时候也是"="格式,如下:
而从redis中取出数据再用JSON.parseArray()转换成List格式时候就会报错
List brandList = JSON.parseArray(String类型,Brand.class)
3.问题解决:
JSON.toJSONString(brands)//brands是对象
在将List类型存入到redis中前使用==JSON.toJSONString()==先把Lis类型转成String类型
八.从数据库查询sku商品信息存到es中时报堆内存溢出异常
1.问题描述
2.问题分析
mysql中表tb_sku大概有32000条数据,一次性把这32000条数据saveall到es中,内存占用太大
3.问题解决
方法一:
注意:-server -XX:PermSize=128M -XX:MaxPermSize=256m
-XX:PermSize:非堆区初始化内存大小
-XX:MaxPermSize:非堆去内存最大值
方法二:
分批存储到es中,一次存个5000~10000条数据
九.ES进行局和分类查询时报错Set fielddata=true
1.问题描述
Failed to execute phase [dfs], all shards failed; shardFailures {[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][0]: RemoteTransportException[[9jF_AW-][172.17.0.2:9300][indices:data/read/search[phase/dfs]]]; nested: IllegalArgumentException[Fielddata is disabled on text fields by default. Set fielddata=true on [spec] in order to load fielddata in memory by uninverting the inverted index.
...
Caused by: NotSerializableExceptionWrapper[: Fielddata is disabled on text fields by default. Set fielddata=true on [spec] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.]; nested: IllegalArgumentException[Fielddata is disabled on text fields by default. Set fielddata=true on [spec] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.];
...
Caused by: java.lang.IllegalArgumentException: Fielddata is disabled on text fields by default. Set fielddata=true on [spec] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.
2.问题分析
es中index的mapping:
在对spec进行聚合分类查询时:
3.问题解决
十.springboot集成thymeleaf中遇到不能返回页面,只返回字符串。
1.问题描述
不能返回页面,只返回字符串。
2.问题分析
在controller中使用了注解@RestController
RestController = Controller + ResponseBody.加上RestController,返回的内容是你return中的内容,如果是return “Hello World”,页面显示的就是Hello World。加上Controller,返回的是return中对应的页面,比如return “hello”,页面的名称是hello。
3.问题解决
修改注解为@Controller
十一.es查询超过第10000条数据时报错
1.问题描述
Failed to execute phase [dfs], all shards failed; shardFailures {[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][0]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][1]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][2]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][3]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][4]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }
...
2019-08-20 15:46:22.688 INFO 8216 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
2019-08-20 15:51:22.690 INFO 8216 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
Failed to execute phase [dfs], all shards failed; shardFailures {[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][0]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][1]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][2]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][3]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }{[9jF_AW-9TfqyX3gVtGpGTQ][myskuinfo][4]: RemoteTransportException[[9jF_AW-][172.17.0.7:9300][indices:data/read/search[phase/dfs]]]; nested: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]; }
...
org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:39)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: QueryPhaseExecutionException[Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level setting.]
...
2.问题分析
主要原因:
这个问题是由于ElasticSearch的默认 深度翻页 机制的限制造成的。ES默认的分页机制一个不足的地方是,比如有5010条数据,当你仅想取第5000到5010条数据的时候,ES也会将前5000条数据加载到内存当中,所以ES为了避免用户的过大分页请求造成ES服务所在机器内存溢出,默认对深度分页的条数进行了限制,默认的最大条数是10000条,这是正是问题描述中当获取第10000条数据的时候报Result window is too large异常的原因。
3.问题解决
方法1 :
增加指定index的max_result_window
curl -XPUT http://127.0.0.1:9200/my_index(改为自己的index)/_settings -d '{ "index" : { "max_result_window" : 500000}}'
3.1kibana中解决
3.2es-head中解决
参考:https://blog.csdn.net/chenhq_/article/details/77507956
方法2 :
在elasticsearch.yml中设置全局index.max_result_window
方法3:
分页使用ES的scroll api实现
十二.通过zuul调用eureka注册的服务
1.问题描述
com.netflix.hystrix.exception.HystrixRuntimeException: SpuFeign#findById(Long) failed and no fallback available.
...
Caused by: java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: spu
...
2.问题分析
3.问题解决
方案一(亲测有效)
在application.properties中添加
ribbon.eureka.enable: true
方案二
添加依赖(有待测试)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
十三.rabbitmq的消费者进行远程调用时报错
1.问题描述
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'topic.queue.spu' in vhost '/', class-id=50, method-id=10)
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66) ~[amqp-client-5.4.3.jar:5.4.3]
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36) ~[amqp-client-5.4.3.jar:5.4.3]
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:494) ~[amqp-client-5.4.3.jar:5.4.3]
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:288) ~[amqp-client-5.4.3.jar:5.4.3]
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:138) ~[amqp-client-5.4.3.jar:5.4.3]
... 14 common frames omitted
2.问题分析
主要原因:reply-text=NOT_FOUND - no queue ‘topic.queue.spu’ in vhost ‘/’
rabbitmq的生产者还未创建消息队列,还未生产消息,此时调用消费者会报错=
3.问题解决
网上其他类似rabbitmq遇到问题的一些答案(只能参考)
1.第一次创建rabbitmq交换机后,更改交换机类型,继续创建时出现。
原因时存在同名的交换机。
比如rabbitmq服务器中已经存在direct类型的交换机(name=“exchange”),你再创建一个同名的但是类型为fanout时就会出错,需要更换名字后再创建。
2.我出现该问题的原因是没有在配置文件application.properties中添加spring.rabbitmq.virtual-host=“”的相关信息 添加后解决 virtual-host可在RabbitMQ主页面virtual-host新建
3.原因:
rabbitmq服务通道是持久通道,该queue 已经存在, 而且通道属性跟最近修改后的属性不一致,而导致无法更新queue.
解决办法:
进入rabbitmq-management 将queue删除即可.
4.解决:访问http://localhost:15672/,在Admin页签中给用户设置相应配置和读写的权限。
十四.rabbitmq消费者监听不到消息
1.问题描述
已知生产者已经创建消息队列,并发送消息,没有报错,但是消费者就是接收不到消息
2.问题分析
可能跟添加rabbitmq依赖时的版本有关系,有些版本不支持@RabbitHandler
3.问题解决
改成@RabbitListener()的方式后,可以正常监听到消息
十四.Oauth2.0密码方式生成令牌时报错:Caused by: java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
1.问题描述
java.lang.RuntimeException: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://192.168.66.57:9001/oauth/token": cannot retry due to server authentication, in streaming mode; nested exception is java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
...
Caused by: org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://192.168.66.57:9001/oauth/token": cannot retry due to server authentication, in streaming mode; nested exception is java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
...
Caused by: java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode
...
2.问题分析
Oauth通过feign远程调用user微服务,通过调用user的findById方法获取当前用户的账号密码信息,然后去生成令牌,但是由于feign的远程调用出现问题,就会无法获得用户信息,无法生成令牌而报错.
3.问题解决
1.启动类上可能忘记添加feign注解:
2.具体可以检查feign的调用问题
十五.微服务与微服务之间controller/service/dao层命名冲突
1.问题描述
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.changgou.OrderApplication]; nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'undoLogServiceImpl' for bean class [com.changgou.goods.service.impl.UndoLogServiceImpl] conflicts with existing, non-compatible bean definition of same name and class [com.changgou.order.service.impl.UndoLogServiceImpl]
...
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'undoLogServiceImpl' for bean class [com.changgou.goods.service.impl.UndoLogServiceImpl] conflicts with existing, non-compatible bean definition of same name and class [com.changgou.order.service.impl.UndoLogServiceImpl]
...
2.问题分析
项目中商品微服务和订单微服务中有重名部分:
3.问题解决
修改任意一个微服务中命名,不再重复冲突既可
十六.不同微服务之间的调用会存在头信息丢失的问题
1.问题描述
com.netflix.hystrix.exception.HystrixRuntimeException: UserFeign#addPoints(Integer) failed and no fallback available.
...
Caused by: feign.FeignException: status 401 reading UserFeign#addPoints(Integer)
2.问题分析
这里实现的功能是用户下单成功后从order服务区调用user服务会存在跨域访问,头信息丢失的问题,所以会调用失败!
3.问题解决
这里可以在公共服务模块中,写一个注入头信息的拦截器,以后每个微服务创建时都在启动类中以@Bean的方式在启动类中注入该拦截器,就可以实现微服务之间的访问,代码如下:
public class FeignInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 如果其微服务工程之间相互调用,那么也需要将令牌信息放入头中
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null){
HttpServletRequest request = attributes.getRequest();
// 获取所有的头信息
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null){
while (headerNames.hasMoreElements()){
// 头信息的:名称(key)
String name = headerNames.nextElement();
// 获取头对应的value
String value = request.getHeader(name);
// 将信息放入RestTemplate中
requestTemplate.header(name, value);
}
}
}
}
}
注入方式如下:
{
HttpServletRequest request = attributes.getRequest();
// 获取所有的头信息
Enumeration headerNames = request.getHeaderNames();
if (headerNames != null){
while (headerNames.hasMoreElements()){
// 头信息的:名称(key)
String name = headerNames.nextElement();
// 获取头对应的value
String value = request.getHeader(name);
// 将信息放入RestTemplate中
requestTemplate.header(name, value);
}
}
}
}
}
注入方式如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190829210611403.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2lfbG92ZV95b3U3,size_16,color_FFFFFF,t_70)