SpringBoot 2.x的开发问题总汇

SpringBoot 2.x的开发问题总汇

1. 微服务开发问题

1. 1 服务降级问题

1.1.1 报错

    { "timestamp": "2019-06-25 10:44:08", "status": 500, "error": "Internal Server Error", "message": "com.netflix.client.ClientException: Load balancer does not have available server for client: tourist-analysis", "path": "/tourism/report" }

服务降级报错

1.1.2 问题分析和方案

  1. 原因:feign集成hystrix需要配置开启

  2. 解决方案:

    feign:
    hystrix:
    enabled: true

1.1.3 参考

  1. Spring Cloud Feign 实现服务降级

1.2 依赖注入失败(mybatis)

1.2.1 错误

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tourism.bigdata.dao.CharTypeDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

1.2.2 问题分析和方案

  1. 原因:dao层的mapper 没有注入
  2. 解决方案:
@Mapper
public interface CharTypeDao extends BaseMapper<CharTypeEntity> {

}

在到层的类上添加@Mapper注解。

1.2.3 正确的配置

  1. 引入依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 添加配置,启动
feign:
  hystrix:
    enabled: true
  1. 添加注解(启动类)
@EnableFeignClients
  1. 在Client上添加降级服务
  • Client定义:
@FeignClient(value = "tourist-analysis", fallback = AnalyzeFallback.class)
public interface AnalyzeClient {
@GetMapping(value = "/tourist/countTourist")
public ResponseResult countTourist(@RequestParam("requestParam") RequestParam requestParam);
 {
  • fallback 定义:
@Slf4j
@Component
public class AnalyzeFallback implements AnalyzeClient {
    @Override
    public ResponseResult countTourist(RequestParam requestParam) {
        log.warn("游客服务的{}不可用","countTourist");
        return null;
    }
}

1.3 服务监控

1.3.1 错误

Field registration in org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration$ServiceRegistryEndpointConfiguration required a single bean, but 2 were found:
	- eurekaRegistration: defined by method 'eurekaRegistration' in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration.class]
	- consulRegistration: defined by method 'consulRegistration' in class path resource [org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.class]

1.3.2 解决方案

添加依赖:
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-netflix-turbine</artifactId>
	</dependency>
或者:
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-netflix-turbine</artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
			</exclusion>
		</exclusions>
	</dependency>

访问:
聚合服务:http://localhost:8201/turbine.stream
单个服务: http://localhost:9001/actuator/hystrix.stream

1.3.3 参考

  1. Spring Cloud Consul综合整理

1.4 consul 替换 eureka 添加密码

1.4.1 解决方案

解决方案:tags 相当于eureka里的metadata-map,大家根据实际需要设置

eureka:
  instance:
    metadata-map:
      user.name: "user"         #These two are needed so that the server
      user.password: "password" 
替换成:
spring
	cloud:
		consul:
		  discovery:
			health-check-interval: 10s
			health-check-path: ${management.server.servlet.context-path}/health
			instance-id: monitor-server
			prefer-ip-address: true
			register: true
			tags: user.name=${spring.security.user.name},user.password=${spring.security.user.password}

1.4.2 参考

  1. spring cloud: 使用consul来替换eureka
  2. SpringBoot2.x搭建SpringBootAdmin2.x

2. 打包问题

2.1 maven将jar 的源码打到仓库

添加插件:

<build>
    <plugins>
        <!-- Source attach plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <executions>
                <execution>
                    <id>attach-sources</id>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

</build>

3. 数据域问题

3.1 MySQL批量更新失败(Mybatis)

  • 问题:语法报错
  • 原因:实际上即使Mybatis完美支持你的sql,你也得看看数据库是否支持。后来发现,原来mysql的批量更新是要我们主动去设置的, 就是在数据库的连接url上设置一下,加上&allowMultiQueries=true 即可。
  • 参考:https://blog.csdn.net/zt_star/article/details/78625923

3.2 MySQL 死锁优化

  • 问题:死锁问题
  • 原因:循环锁、慢SQL
  • 参考:https://www.cnblogs.com/gdwkong/articles/8505125.html

3.3 MySQL Group By 有问题:

  • 问题:mysql命令gruop by报错this is incompatible with sql_mode=only_full_group_by
  • MySQL版本问题
  • 解决办法
在mysql 工具 搜索或者插入数据时报下面错误:
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database_tl.emp.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
原因:
看一下group by的语法:
select 选取分组中的列+聚合函数 from 表名称 group by 分组的列 
从语法格式来看,是先有分组,再确定检索的列,检索的列只能在参加分组的列中选。
我当前Mysql版本5.7.17,
再看一下ONLY_FULL_GROUP_BY的意思是:对于GROUP BY聚合操作,如果在SELECT中的列,没有在GROUP BY中出现,那么这个SQL是不合法的,因为列不在GROUP BY从句中,也就是说查出来的列必须在group by后面出现否则就会报错,或者这个字段出现在聚合函数里面。
 
查看mysql版本命令:select version();
查看sql_model参数命令:
SELECT @@GLOBAL.sql_mode;
SELECT @@SESSION.sql_mode;
发现:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
第一项默认开启ONLY_FULL_GROUP_BY,
 
解决方法:
1.只选择出现在group by后面的列,或者给列增加聚合函数;(不推荐)
2.命令行输入:
set @@GLOBAL.sql_mode='';
set sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
 
默认关掉ONLY_FULL_GROUP_BY!
 
这个时候 在用工具select 一下
SELECT @@sql_mode;
SELECT @@GLOBAL.sql_mode;
 
发现已经不存在ONLY_FULL_GROUP_BY ,感觉已经OK。但是如果你重启Mysql服务的话,发现ONLY_FULL_GROUP_BY还是会存在的
 
想要彻底解决这个问题 就得去改my.ini 配置(如果你们mysql 没有这个文件,就把my-default.ini 改成my.ini,我这个版本就是没有my.ini配置问题)
 
在 [mysqld]和[mysql]下添加
 sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

4. Springboot 开发问题

4.1 开发基本异常

4.1.1文件保存失败

  • 问题:
    java.io.IOException:The temporary upload location[/tmp/tomcat.809639411644325061.8080/work/Tomcat/localhost/ROOT] is not valid
  • 原因:
    在Linux 系统中,SpringBoot 应用服务在启动(java -jar 命令启动服务)的时候,会在操作系统的/tmp目录下生成一个tomcat*的文件目录,上传的文件先要转换成临时文件保存在这个文件夹下面。由于临时/tmp目录下的文件,在长时间(10天)没有使用的情况下,就会被系统机制自动删除掉。所以如果系统长时间无人问津的话,就可能导致上面这个问题。
  • 解决方案:
    一.临时的,直接重新启动项目就行,会重新建立临时文件夹
    二.在配置文件中配置tomcat的临时目录:
    server.tomcat.basedir=/home/temp
    三. 写个配置类,通过@Bean的方式配置目录:
    /**
  • 文件上传临时路径
    */
    @Bean
    MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setLocation(“/home/temp”);
    return factory.createMultipartConfig();
    }
  • 参考:https://blog.csdn.net/a513684882/article/details/100917953

4.2 MapperScan导致SpringBoot自动注入出现duplicate

  • 问题:MapperScan导致SpringBoot自动注入出现duplicate
  • 原因:
    在SpringBoot中我们配置Mybatis的扫描是很简单的,最简单粗暴的方法是直接在类上注解 @MapperScan(“你的项目根包”),
    然后你就会惊喜的发现,Mybatis帮你把所有的接口都做了一个动态代理…为所有的接口都做了一个实现类,无差别攻击。
    这是因为,Mybatis的默认机制是会对MapperScan中basePackage包下的所有接口都生成一个代理实现类。
    这个代理类会和我们自定义添加了组件注解的实现类产生冲突,从而导致出现重复声明
  • 解决方案:
  1. 指定MapperScan扫描特定的mapper包,而不是直接扫描根目录

4.3 响应式编程

  • 问题:Reactor之发射器(Flux、Mono)创建函数
  • 参考:https://www.jianshu.com/p/611f3667c4d2

4.4 JasperReport生成PDF中文不显示处理

  • 参考:JasperReport生成PDF中文不显示处理(https://blog.csdn.net/clj198606061111/article/details/78536396)

4.5 corn表达式详解

  • 参考:https://blog.csdn.net/loongqiao/article/details/88265246

4.6 Java 中 double 在计算时精度丢失的问题

  • 参考: https://blog.csdn.net/AD_plus/article/details/90694399

4.7 Socket和websocket的区别

说到 websocket 我觉得有必要说下跟 socket 的区别。
软件通信有七层结构,下三层结构偏向与数据通信,上三层更偏向于数据处理,中间的传输层则是连接上三层与下三层之间的桥梁,每一层都做不同的工作,上层协议依赖与下层协议。基于这个通信结构的概念。
Socket 其实并不是一个协议,是应用层与 TCP/IP 协议族通信的中间软件抽象层,它是一组接口。当两台主机通信时,让 Socket 去组织数据,以符合指定的协议。TCP 连接则更依靠于底层的 IP 协议,IP 协议的连接则依赖于链路层等更低层次。
WebSocket 则是一个典型的应用层协议。
总的来说:Socket 是传输控制层协议,WebSocket 是应用层协议。

4.7.1 七层协议

应用层
与其它计算机进行通讯的一个应用,它是对应应用程序的通信服务的。例如,一个没有通信功能的字处理程序就不能执行通信的代码,从事字处理工作的程序员也不关心OSI的第7层。但是,如果添加了一个传输文件的选项,那么字处理器的程序就需要实现OSI的第7层。示例:TELNET,HTTP,FTP,NFS,SMTP等。
表示层
这一层的主要功能是定义数据格式及加密。例如,FTP允许你选择以二进制或ASCII格式传输。如果选择二进制,那么发送方和接收方不改变文件的内容。如果选择ASCII格式,发送方将把文本从发送方的字符集转换成标准的ASCII后发送数据。在接收方将标准的ASCII转换成接收方计算机的字符集。示例:加密,ASCII等。
会话层
它定义了如何开始、控制和结束一个会话,包括对多个双向消息的控制和管理,以便在只完成连续消息的一部分时可以通知应用,从而使表示层看到的数据是连续的,在某些情况下,如果表示层收到了所有的数据,则用数据代表表示层。示例:RPC,SQL等。
传输层
这层的功能包括是否选择差错恢复协议还是无差错恢复协议,及在同一主机上对不同应用的数据流的输入进行复用,还包括对收到的顺序不对的数据包的重新排序功能。示例:TCP,UDP,SPX。
网络层
这层对端到端的包传输进行定义,它定义了能够标识所有结点的逻辑地址,还定义了路由实现的方式和学习的方式。为了适应最大传输单元长度小于包长度的传输介质,网络层还定义了如何将一个包分解成更小的包的分段方法。示例:IP,IPX等。
数据链路层
它定义了在单个链路上如何传输数据。这些协议与被讨论的各种介质有关。示例:ATM,FDDI等。
物理层
OSI的物理层规范是有关传输介质的特性,这些规范通常也参考了其他组织制定的标准。连接头、帧、帧的使用、电流、编码及光调制等都属于各种物理层规范中的内容。物理层常用多个规范完成对所有细节的定义。示例:Rj45,802.3等。

4.8 Spring Boot返回对象时,把Long类型转换为String

  • 方案
    自定义ObjectMapper
/**
 * 返回Long转换为String
 */
public class JacksonMapper extends ObjectMapper {

  public JacksonMapper() {
    super();
    this.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    this.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
    this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.setSerializationInclusion(Include.NON_NULL);

    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
    simpleModule.addSerializer(long.class, ToStringSerializer.instance);
    registerModule(simpleModule);

  }
}

把MappingJackson2HttpMessageConverter 设置给HttpMessageConverter

/**
 * 
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Autowired
  private HttpMessageConverters httpMessageConverters;

  /**
   * MappingJackson2HttpMessageConverter 实现了HttpMessageConverter 接口,
   * httpMessageConverters.getConverters() 返回的对象里包含了MappingJackson2HttpMessageConverter
   * @return
   */
  @Bean
  public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
    return new MappingJackson2HttpMessageConverter(new JacksonMapper());
  }


  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.addAll(httpMessageConverters.getConverters());
  }
}

  • 参考:https://blog.csdn.net/u012620150/article/details/90033244

4.9 springboot自定义事件的发布和监听

1、自定义事件
2、定义监听器
3、发布事件
参考:https://www.cnblogs.com/wangpipi/p/11134175.html

4.10 热部署

  • 依赖
<!--devtools热部署-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
    <scope>true</scope>
</dependency>
  • 配置
spring:
  devtools:
    restart:
      #设置开启热部署
      enabled: true
      #重启目录
      additional-exclude: src/main/java
      exclude: resources/**
  thymeleaf:
    encoding: utf-8
    #页面不加载缓存,修改即时生效
    cache: false
    mode: HTML5

4.11 Spring Boot LocalDateTime格式处理

参考:https://blog.csdn.net/junlovejava/article/details/78112240?utm_source=blogxgwz9

5. 系统层面开发问题

5.1当linux报 “-bash: fork: 无法分配内存”

  • 问题
    -bash: fork
  • 原因
    版本系统的内核pid参数比较小(默认设置的是32768)
  • 解决方案:
echo "kernel.pid_max=64000" >>/etc/sysctl.conf
sysctl -p 
  • 参考:https://blog.csdn.net/cfaster/article/details/53065738

5.2 [Java] Socket报错打开文件过多

  • 问题:打开文件超过系统限制
  • 原因:系统限制
  • 解决方案:
    1. 临时解决方案:ulimit -n 4096
    2. 永久解决方案:/etc/security/limits.conf
  • 参考:

5.3 java.net.NoRouteToHostException: No route to host (Host unreachable) 解决(docker 部署xxl-job)

  • 问题:
    在master节点上,启动slave1中的impala,报slave1, No route to host。
    从master 可以 ssh slave1(且为免密码登陆),为什么还报No route to host错?郁闷了一下午,才想起可能是防火墙的原因:
    service iptables status (查看防火墙状态),真的是防火墙没关。。。。。
  • 原因:防火墙没关
  • 解决方案:
    解决:未关闭防火墙
    1)永久性生效,重启后不会复原
    关闭:chkconfig iptables off
    2)即时生效,重启后复原
    关闭:service iptables stop
  • 参考:https://blog.csdn.net/weixin_39848393/article/details/79722880

5.4 解决docker 容器内访问宿主机“No route to host”的问题

请顺序运行以下命令:
nmcli connection modify docker0 connection.zone trusted

systemctl stop NetworkManager.service
firewall-cmd --permanent --zone=trusted --change-interface=docker0
systemctl start NetworkManager.service
nmcli connection modify docker0 connection.zone trusted
systemctl restart docker.service

5.5 浏览器

5.5.1 请求头

  • 注释:web开发技术 > http > http headers > Access-Control-Expose-Headers
  • 参考:
    https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)

5.5.2 Access-Control-Max-Age

浏览器的同源策略,就是出于安全考虑,浏览器会限制从脚本发起的跨域HTTP请求(比如异步请求GET, POST, PUT, DELETE, OPTIONS等等),所以浏览器会向所请求的服务器发起两次请求,第一次是浏览器使用OPTIONS方法发起一个预检请求,第二次才是真正的异步请求,第一次的预检请求获知服务器是否允许该跨域请求:如果允许,才发起第二次真实的请求;如果不允许,则拦截第二次请求。
Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,在此期间不用发出另一条预检请求。
例如:
resp.addHeader("Access-Control-Max-Age", "0"),表示每次异步请求都发起预检请求,也就是说,发送两次请求。
resp.addHeader("Access-Control-Max-Age", "1800"),表示隔30分钟才发起预检请求。也就是说,发送两次请求

Nginx  配置:
location /wechat/ {
add_header ‘Access-Control-Max-Age’ 1728000;
proxy_pass http://wechat/rest/;
}

6. 注册中心

6.1 consul

./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c1 -ui -client 0.0.0.0 -bind 192.168.1.150 -join 192.168.1.149
./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c2 -ui -client 0.0.0.0 -bind 192.168.1.151 -join 192.168.1.149
./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c3 -ui -client 0.0.0.0 -bind 192.168.1.152 -join 192.168.1.149

参考  https://www.cnblogs.com/northeastTycoon/p/10462187.html
-- 单点:

nohup ./consul agent --server=true --bootstrap-expect=1 --client=0.0.0.0 -ui -bind=192.168.10.24 --data-dir /local/register/consul-data/consul-node-192.168.10.24  1>consul.log 2>&1 &

-- 集群

nohup ./consul agent -server -bootstrap-expect=3 -data-dir=/tmp/consul -node=192.168.10.6 -bind=192.168.10.6 -client=0.0.0.0 -ui &
nohup ./consul agent -server -bootstrap-expect=3 -data-dir=/tmp/consul -node=192.168.10.7 -bind=192.168.10.7 -client=0.0.0.0 -ui &
nohup ./consul agent -server -bootstrap-expect=3 -data-dir=/tmp/consul -node=192.168.10.35 -bind=192.168.10.35 -client=0.0.0.0 -ui &

./consul join 192.168.10.6

-- 查看状态
./consul operator raft list-peers

-- 查看集群
./consul members

--查看信息
./consul info


-- 相关参数
相关配置:
顺序 命令行>环境变量>配置文件
重加载:SIGHUP信号触发。
命令行配置:
-bootstrap:启动模式,此模式下,节点可以选举自己为leader,一个数据中心只能有一个此模式启动的节点。机群启动后,新启动的节点不建议使用这种模式。
-bootstrap-expect:设定一个数据中心需要的服务节点数,可以不设置,设置的数字必须和实际的服务节点数匹配。consul会等待直到数据中心下的服务节点满足设定才会启动集群服务。初始化leader选举,不能和bootstrap混用。必须配合-server配置。
-bind:绑定的内部通讯地址,默认0.0.0.0,即,所有的本地地址,会将第一个可用的ip地址散播到集群中,如果有多个可用的ipv4,则consul启动报错。[::]ipv6,TCP UDP协议,相同的端口。防火墙配置。
-client:客户端模式,http dns,默认127.0.0.1,回环令牌网址
-config-file:配置文件位置
-config-dir:配置文件所在文件夹,会加载其下所有配置文件,.json或者.hcl文件,加载顺序为字母表顺序;可用配置多个此配置,从而加载多个文件夹,子文件夹的配置不会被加载。
-config-format:配置文件格式,配置了,则加载相应个是的文件。不配置,则consul自动识别。
-data-dir:状态数据存储文件夹,所有的节点都需要。文件夹位置需要不收consul节点重启影响,必须能够使用操作系统文件锁,unix-based系统下,文件夹文件权限为0600,注意做好账户权限控制,
-datacenter:数据中心名称,默认dc1,一个数据中心的所有节点都必须在一个LAN中。
-dev:开发模式,去掉所有持久化选项,内存服务器模式。
-disable-host-node-id:不使用host信息生成node ID,适用于同一台服务器部署多个实例用于测试的情况。随机生成nodeID
-dns-port:v7.0以后,自定义dns 端口,覆盖默认8600
-enable-script-checks:是否允许使用脚本进行健康检查,默认false,最好配置enable acl
-encrypt:consul网络通讯加密key,base64加密,16比特;consul keygen产生。集群中的每个实例必须提供相同的,只需提供一次,然后会保存到数据文件。重启自动加载。consul节点启动后提供,会被忽略。
-hcl:添加hcl格式配置,和已有的配置合并。可以使用多个此配置。
-http-port:http api端口,覆盖默认的8500。适用于云环境指定。
-log-file:日志记录文件,如果没有提供文件名,则默认Consul-时间戳.log
-log-level:日志级别,默认info,包含:trace,debug,info,warn,err;consul monitor监控
-log-rotate-bytes:新日志文件生成大小阈值。
-log-rotate-rotation:新日志生成时间阈值
-join:需要加入的其它节点地址,可以多次使用,加入多个节点。
-retry-join:会进行加入重试,适用于认定加入节点最终会正常的情况。ipv4,ipv6,dns
-retry-interval:上述,重试间隔,默认30s
-retry-max:重试次数,默认0,无限次重试
-join-wan, -retry-join-wan, -retry-interval-wan, -retry-max-wan 
-node:节点名称,默认主机名
-node-id:节点ID,
-pid-file:consul 存储 pid 的文件位置,用于主动发信号。如停止节点,重载配置等。
-protocol:使用的协议,升级时使用。consul -v查看协议版本
-raft-protocol:使用raft协议版本,默认3
-raft-snapshot-threshold:raft执行快照,提交次数阈值。一般不需要设置,io密集型应用可以调高。避免所有的节点同一时间快照。此值过大,会造成相应日志文件变大,节点重启恢复会耗费更长时间。1.1.0后,默认16384,之前8192.
-raft-snapshot-interval:执行快照间隔,影响类似上个配置,1.1.0后默认30s,之前5s。
-rejoin:节点会尝试重新加入集群。
-server:服务端节点模式。
-server-port:服务端RPC端口,v1.2.2后提供。
-non-voting-server:服务节点不参与选举,接受日志复制,用于横向扩展,服务查询请求。(类比zookeeper 观察者节点)
-syslog:linux OSX系统,配置日志输出到系统日志。
-ui:内置web ui界面。
-ui-dir:web ui 资源文件夹,使用此配置,则不需也不能使用再-ui配置。
默认使用端口:
服务端RPC:默认8300,TCP。
Serl LAN:处理LAN gossip,默认8301,TCP UDP。
Serl WAN:处理LAN gossip,默认8302,TCP UDP。
HTTP API:8500,TCP.
DNS:8600,TCP,UDP.
可重载配置:
Log level
Checks
Services
Watches
HTTP Client Address
Node Metadata
Metric Prefix Filter
Discard Check Output
RPC rate limiting

-- 节点重连


-- 集群通信机制
http://www.sohu.com/a/258581510_468635
https://www.consul.io/docs/agent/basics.html

6.2 Nacos

  • 问题:nacos报错:java.lang.IllegalArgumentException: Param ‘serviceName‘ is illegal, serviceName is blank
  • 原因:启动加载配置文件问题
  • 解决方案:
<!--启动程序解决Nacos: serviceName is blank问题-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

7. 注册网关

7.1 Gateway

7.1.1 启动报错

  • 问题:gateway启动报错:org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer’ that could not be found
  • 原因:根据上面描述(Description)中信息了解到GatewayAutoConfiguration这个配置中找不到ServerCodecConfig这个Bean。
    spring cloud gateway server项目是一个spring boot项目,在启动的时候会去加载它的配置,其中有一个叫做GatewayClassPathWarningAutoConfiguration的配置类中有这么一行代码:
@Configuration
@ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet")
protected static class SpringMvcFoundOnClasspathConfiguration {
 	public SpringMvcFoundOnClasspathConfiguration() {
		log.warn(BORDER+"Spring MVC found on classpath, which is incompatible with 				Spring 	Cloud Gateway at this time. "+
	"Please remove spring-boot-starter-web dependency."+BORDER);
	} 
}
  • 解决方案:将pom.xml中关于spring-boot-start-web模块的jar依赖去掉。
    在类路径上找到的Spring MVC,此时它与Spring Cloud网关不兼容。请删除spring-boot-start-web依赖项。
    因为spring cloud gateway是基于webflux的,如果非要web支持的话需要导入spring-boot-starter-webflux而不是spring-boot-start-web。

7.1.2 webFlux 和web冲突

  • 问题:org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
  • 原因:因为 webFlux 和web冲突
  • 解决方案:
<!--排除:-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <optional>true</optional>
</dependency>
  • 参考:https://blog.csdn.net/yichen0429/article/details/98203775

7.2 网关鉴权

在这里插入图片描述

7.2.1 解决办法:要不使用动态数据源

info:
  nacos:
    address: 192.22.1.21:8500
server:
  port: 9201
spring:
  application:
    name: api-system-manage
  profiles:
    active: dev
  main:
    allow-bean-definition-overriding: true
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  servlet:
    multipart:
      maxFileSize: 30MB  #单位必须大写MB或不写(即为B)
      maxRequestSize: 30MB
  cloud:
    nacos:
      config:
        server-addr: ${info.nacos.address}
        file-extension: yaml
        prefix: ${spring.application.name}
      discovery:
        server-addr: ${info.nacos.address}
  datasource:
    dynamic:
      # 是否开启 SQL日志输出,生产环境建议关闭,有性能损耗
      p6spy: true
      hikari:
        connection-timeout: 30000
        max-lifetime: 1800000
        max-pool-size: 15
        min-idle: 5
        connection-test-query: select 1
        pool-name: SystemHikariCP
      # 配置默认数据源
      primary: primary
      datasource:
        # 数据源-1,名称为 primary
        primary:
          username: root
          password: Sd@2019
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
          url: jdbc:p6spy:mysql://192.22.1.21:3306/system_manage?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
        # 数据源-2,名称为 test  47.92.145.171
  #        test:
  #          username: root
  #          password: 123456
  #          driver-class-name: com.mysql.cj.jdbc.Driver
  #          url: jdbc:mysql://127.0.0.1:3306/febs_test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
  aop:
    proxy-target-class: true
  devtools:
    restart:
      exclude:  static/**,public/**
      enabled:  true
  messages:
    encoding: utf-8

  redis:
    database: 0
    host: 192.22.1.21
    port: 6379
    password: Sd@redis
    jedis:
      pool:
        min-idle: 8
        max-idle: 500
        max-active: 2000
        max-wait: 20000
    timeout: 1200

7.2.2 要不使用druid连接池(需要druid依赖)

info:
  nacos:
    address: 192.22.1.21:8500
server:
  port: 9201

spring:
  application:
    name: api-system-manage
  profiles:
    active: dev
  devtools:
    restart:
      enabled: true
  main:
    allow-bean-definition-overriding: true
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  servlet:
    multipart:
      maxFileSize: 30MB  #单位必须大写MB或不写(即为B)
      maxRequestSize: 30MB
  cloud:
    nacos:
      config:
        server-addr: ${info.nacos.address}
        file-extension: yaml
        prefix: ${spring.application.name}
      discovery:
        server-addr: ${info.nacos.address}
  # 配置数据源
  datasource:
    hikari:
      auto-commit: true
      connection-test-query: SELECT 1
      connection-timeout: 30000
      idle-timeout: 30000
      max-lifetime: 1800000
      maximum-pool-size: 15
      minimum-idle: 5
      pool-name: DatebookHikariCP
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:mysql://192.22.1.21:3306/system_manage?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull
    username: root
    password: Sd@2019
    type: com.zaxxer.hikari.HikariDataSource
  redis:
    database: 0
    host: 192.22.1.21
    port: 6379
    password: sd@redis
    lettuce:
      pool:
        min-idle: 8
        max-idle: 500
        max-active: 2000
        max-wait: 10000
    timeout: 1800
feign:
  hystrix:
    enabled: true

# mybatis-plus相关配置
mybatis-plus:
  # xml扫描,多个目录用逗号或者分号分隔(告诉 mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:mapper/**/*.xml
  # 以下配置均有默认值,可以不设置
  global-config:
    db-config:
      #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
      id-type: ID_WORKER
      #字段策略 IGNORED:"忽略判断"  NOT_NULL:"非 NULL 判断")  NOT_EMPTY:"非空判断"
      field-strategy: NOT_EMPTY
      #数据库类型
      db-type: MYSQL
    banner: off
  configuration:
    # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
    map-underscore-to-camel-case: true
    # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
    call-setters-on-nulls: true
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 注册后在 mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名
  type-aliases-package: com.smart.system.common.entity
  #启动时是否检查 MyBatis XML 文件的存在,默认不检查
  check-config-location: false


# 暴露监控端点
management:
  endpoints:
    web:
      exposure:
        include: '*'

# 日志配置
logging:
  level:
    com.smart: debug
    org.springframework: warn
    com.alibaba.nacos.client.naming: error

7.3 Nacos

7.3.1 Nacos 的基本配置

  • 集成nacos 实现配置管理
  • 如果使用本地配置,就不要引入nacos-config 相关依赖和配置
<!--<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>-->

spring:
  application:
    name: message-manage
  cloud:
    nacos:
#      config:
#        server-addr: ${info.nacos.address}
#        file-extension: yaml
#        prefix: ${spring.application.name}
  • 生效本地local
    在这里插入图片描述
    在这里插入图片描述
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值