precondition :jdk、SpringBoot project 、Nacos、Linux The server ( But there is no )

Specific version :jdk11、SpringBoot 2.3.5.RELEASE、Nacos 2.0.3、Centos 6

The goal is :SpirngBoot Project use Nacos Dynamically manage project configuration as a configuration center

Refer to the end of this article for relevant questions and answers

First text :chenetchen.ltd, Personal blog site .

Preface

Use SringBoot Framework development projects , Although there is no need to be in Tomcat Configuration on , You can type the project as jar Publish the package on the server , But if you need to modify the configuration file , Need to stop the project , Use vim open jar Package modification configuration file , And then restart the project .

The process is complicated , And you need to start and stop the project , It requires professionals to operate on the server . In previous work , Learned JMX, Parameters can be dynamically obtained or modified , however JMX The main function of is to monitor , Not as a configuration , And call JMX Connection is also troublesome , Learning costs more , Use JMX To view and manage parameters, you need to use jconsole Tools , There are also learning costs , It also requires professionals to operate .

So , Think back to the distributed components learned before ,Nacos Into my choice

Nacos

Nacos It is an open source software under Alibaba , Support service registration and discovery 、 Components of configuration management and microservice Management .Nacos The goal is to replace the commonly used registry (Zookeeper、Eureka etc. ), And the configuration center (Spring Cloud Config etc. ).Nacos It integrates the functions of registration center and configuration center .

Based on this , Although it is SpirngBoot project , Service registration and discovery cannot be used , But you can use Nacos The function of configuration center , Dynamically manage the configuration file of the project .

SpringBoot Use Nacos

Maven To configure

According to official documents ——Nacos Spring Boot Quick start , stay Spirng Boot Project Maven Introduction in nacos-config-spring-boot-starter rely on

<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>

It should be noted that , Online for Spring Boot Project used Nacos Which dependence is , There is an incorrect version , Quite a number of Posts and blogs , It's about spring-cloud-starter-alibaba-nacos-discovery and spring-cloud-starter-alibaba-nacos-config, Although these two can also be in Spring Boot Use in , But the configuration is more cumbersome . You can refer to SpringBoot Integrate nacos Implementation configuration center ( Configure dynamic updates )

Nacos To configure

start-up Nacos

For the environment in this article , That a single Spirng Boot For non distributed cluster projects ,Nacos It needs to be started in the form of a single machine .

stay Windows Modify the /nacos/bin In the catalog startup.cmd Script files , Will be one of the set MODE="cluster" It is amended as follows set MODE="standalone", That is to say Nacos The stand-alone start of .

Configuration Management

Nacos After successful startup ( This article defaults to testing in Windows Single machine startup in environment Nacos, Keep default configuration ), visit localhost:8848/nacos, Use naocs/nacos Sign in Nacos platform .

Click configuration list in configuration management on the left , Then click the plus sign button above the main body list on the right page , Add the configuration ,Data Id by test, Grouping defaults to , Format selection properties, Configuration content is

useLocalCache=true

After publishing successfully , return .

Project configuration

Nacos To configure

There are two ways to configure a project , One is Using annotations , stay SpringBoot Use... On the main startup class of the project

@NacosPropertySource(dataId = "test", autoRefreshed = true)
dataId:Nacos Configuration configured in ID
autoRefreshed: Turn on auto refresh

Another way is to use a configuration file , Because I mentioned Spring Boot Is used in nacos-config-spring-boot-starter, Instead of Cloud Do you rely on , So here is unable Use bootstrap Profile's ( If you want to use bootstrap To configure , Need to introduce cloud Related configuration files ), Directly in application In the configuration file nacos Related configuration .

nacos:
config:
type: yaml
server-addr: 127.0.0.1:8848
context-path: nacos
data-id: test
auto-refresh: true
bootstrap:
enable: true

It should be noted that , In the above configuration , There are individual configurations that need attention , On this issue , see SpringBoot2 Integrate nacos( One )

Test code

see Nacos Official demo, Write the following test classes (SpringBoot The project needs to be introduced web rely on )

@Controller
public class Test {
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache; @RequestMapping(value = "/get", method = RequestMethod.GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}

Start project ( If in the configuration file ——Nacos Project port is not specified in both configuration and project configuration , And 80 Port occupied , Note that the added amount is the project port configuration ,server.prot=xxx, Configure in Nacos or application In the configuration file )

visit /get test , Return to true It indicates that the SpringBoot Get the item correctly Nacos Configuration in .

Version of the problem

If the basic process above goes well , So congratulations on not having a version problem ; If Nacos Boot failure 、 Project startup failed 、 Cannot get value, etc , Then the next part should solve your problem .

SpirngBoot and Nacos Spring Boot

First of all SpringBoot Version and Nacos Of pom Document version , This problem usually occurs when the project fails to start , This is because SpringBoot Version and nacos-config-spring-boot-starter Version issue for . The following errors usually occur :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nacosConfigurationPropertiesBinder': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:315) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1206) ~[spring-beans-5.3.2.jar:5.3.2]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:225) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.3.2.jar:5.3.2]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311) ~[spring-beans-5.3.2.jar:5.3.2]
... 20 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
at com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder.<init>(NacosBootConfigurationPropertiesBinder.java:51) ~[nacos-config-spring-boot-autoconfigure-0.2.7.jar:0.2.7]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_181]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_181]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_181]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:212) ~[spring-beans-5.3.2.jar:5.3.2]
... 22 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_181]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_181]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_181]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_181]
... 28 common frames omitted

Error message: create a file named 'nacosConfigurationPropertiesBinder' Of bean Failure . This is because nacos-config-spring-boot-starter Supported by SpringBoot The version is lower than the version currently used by the project , and SpringBoot stay 2.4 Then deleted ConfigurationBeanFactoryMetadata, Need to put SpringBoot The version of is downgraded to 2.3.x.

Nacos Spring Boot and JDK

Yes , you 're right ,JDK There is also a foot in here , It is possible that JDK The version of .

stay JDK11 In the case of ,nacos-config-spring-boot-starter Version is too low , The project starts but throws an exception , But when accessing test code , Can't get Nacos Values configured in the configuration center .

Via netizens @yvioo test , stay JDK11 Next , Use nacos-config-spring-boot-starter Version is 0.2.7 And above , Can be successfully obtained Nacos Configure the value of the center ( When I tested, I still failed to get ), It is recommended to use 0.2.10 edition .

Deploy the project to Linux On

After a series of tests above ,SpringBoot The project has been able to obtain complete Nacos Configuration center , Now? , The environment needs to be deployed to Linux On the server .

Linux install Nacos

Believe online about Linux Upper Department Nacos There are countless tutorials , But most of the tutorials are not detailed enough in my eyes , There is no mention of all kinds of bug, Under the test of my starling little prince , Sure enough, it triggered all kinds of bug, So , How to install... Will not be described in more detail below nacos, But how to solve it bug.

Give a brief overview of Linux install Nacos, Download from the official nacos.tar.gz After installing the package , Unzip to /usr/local Under the table of contents , The installation is successful , If everything goes well , image Windows Modify the startup mode , After changing from cluster to stand-alone , direct ./startup.sh -m standalone You can start Nacos 了 .

Java Environmental problems

Nacos Boot failure , First check Java Environmental Science ,Nacos It's actually jar package , Need to use Java To start up .

If you are familiar with shell Script , You can see in the nacos/bin In the catalog startup.sh Script , Yes, I have access to Java Environmental .

[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=$JAVA_HOME/java/jdk-11.0.11
[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=/usr/java
[ ! -e "$JAVA_HOME/bin/java" ] && JAVA_HOME=/opt/taobao/java
[ ! -e "$JAVA_HOME/bin/java" ] && unset JAVA_HOME

First, you can use the command echo $JAVA_HOME Check in /etc/profile As defined in JAVA_HOME route , contrast Nacos Get from the startup script JAVA_HOME route .

JDK11 problem

Yes , you 're right ,JDK11 Here comes the question of , stay JDK11 Start in an environment Nacos It can also fail , Reference resources Linux Next use JDK11 Deploy Nacos Initiate error reporting :Could not find or load main class, You need to start the script startup.sh Replace with the following configuration in

JAVA_OPT_EXT_FIX="-Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${JAVA_HOME}/lib/ext"
Replace with
JAVA_OPT="${JAVA_OPT} -Djava.ext.dirs=${JAVA_HOME}/jre/lib/ext:${JAVA_HOME}/lib/ext" echo "$JAVA $JAVA_OPT_EXT_FIX ${JAVA_OPT}"
Replace with
echo "$JAVA ${JAVA_OPT}" echo "$JAVA $JAVA_OPT_EXT_FIX ${JAVA_OPT}" > ${BASE_DIR}/logs/start.out 2>&1 &
nohup "$JAVA" "$JAVA_OPT_EXT_FIX" ${JAVA_OPT} nacos.nacos >> ${BASE_DIR}/logs/start.out 2>&1 &
Replace with
echo "$JAVA ${JAVA_OPT}" > ${BASE_DIR}/logs/start.out 2>&1 &
nohup $JAVA ${JAVA_OPT} nacos.nacos >> ${BASE_DIR}/logs/start.out 2>&1 &

You can start it successfully .

JVM Memory problems

After the replacement , To start the , At this time, it should be able to start successfully ,ps -ef|grep nacos The command can also successfully see nacos Of pid, But when you access the server nacos Address time , Found unable to request ( Port occupancy is excluded by default , Firewall does not open ports and other issues ), And reuse ps Command view , Will find nacos It stops automatically .

This is because nacos2.0 edition , ... is specified by default in the configuration file jvm Size . It's also in Nacos Start script for startup.sh In file .

#===========================================================================================
# JVM Configuration
#===========================================================================================
if [[ "${MODE}" == "standalone" ]]; then
JAVA_OPT="${JAVA_OPT} -Xms512m -Xmx512m -Xmn256m"
JAVA_OPT="${JAVA_OPT} -Dnacos.standalone=true"
else
if [[ "${EMBEDDED_STORAGE}" == "embedded" ]]; then
JAVA_OPT="${JAVA_OPT} -DembeddedStorage=true"
fi
JAVA_OPT="${JAVA_OPT} -server -Xms2g -Xmx2g -Xmn1g -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=320m"
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${BASE_DIR}/logs/java_heapdump.hprof"
JAVA_OPT="${JAVA_OPT} -XX:-UseLargePages" fi if [[ "${FUNCTION_MODE}" == "config" ]]; then
JAVA_OPT="${JAVA_OPT} -Dnacos.functionMode=config"
elif [[ "${FUNCTION_MODE}" == "naming" ]]; then
JAVA_OPT="${JAVA_OPT} -Dnacos.functionMode=naming"
fi

Among them JAVA_OPT="${JAVA_OPT} -Xms512m -Xmx512m -Xmn256m" One line specifies JVM Initial and maximum capacity of .

-Xms: Set the amount of memory occupied when the program starts 
-Xmx: Set the maximum amount of memory that can be used during the running of the program
-Xmn: The size of the new generation

in the light of Linux The system can be successfully started by manually modifying the system capacity .

JAVA_OPT="${JAVA_OPT} -Xms100m -Xmx256m -Xmn200m"

thus ,SpirngBoot Project use Nacos As configuration center , Dynamic management configuration completed .

Reference material

  1. Nacos Spring Boot Quick start

  2. SpringBoot2 Integrate nacos( One )

  3. nacos-spring-boot-config-example

  4. spring boot Use nacos Practice as a configuration center

  5. SpringBoot bootstrap The configuration file is not in effect

  6. Linux Next use JDK11 Deploy Nacos Initiate error reporting :Could not find or load main class

  7. centos perhaps linux Your ECS always fails to start nacos To solve the problem

SpringBoot Project use Nacos More related articles as the configuration center

  1. Nacos( Four ):SpringCloud Access in the project Nacos As configuration center

    Preface Through the first two articles : Nacos( Two ):Nacos And OpenFeign The docking use of Nacos( 3、 ... and ):SpringCloud Access in the project Nacos As a registry I think you're right Nacos As a basic registry ...

  2. Nacos series : be based on Nacos Configuration center

    Preface Before reading the text , I'd like to ask you to review how the companies you've been in manage configuration , I think there should be the following ways : 1. Hard encoding There's nothing that's not configured , Write it directly in the code , For example, using constant classes advantage : Friendly to development , Development clearly knows generation ...

  3. java The road of Architecture -( Micro service topics )feign The basic use of and nacos Configuration center

    Last return : Last time we said ribbon Basic use of , Including the internal algorithms , Fine grained configuration of algorithms , And how we implement our own algorithms , It's mainly about some basic knowledge , Not yet ribbon You can go back to the last article ...

  4. nacos As a configuration center, dynamic refresh @RefreshScope After adding, the value is null A question of

    Before springboot The project constant class has the following form : @Component @RefreshScope//nacos When configuring the center, add public class Constants { @Value(" ...

  5. How do you use Nacos As a configuration center ?

    If you use spring-cloud-alibaba Microservice technology stack Configuration files unique to a single service That is, remove the state of the application , Configure unified externalization management , It is convenient for horizontal expansion . Integration steps : If I have an application app-desig ...

  6. ****** You can use SpringBoot The project is packaged separately lib, Configuration and resource files

    spring-boot After multi module packaging , Unable to find classes in other modules https://blog.csdn.net/Can96/article/details/96172172 About SpringBoot Project packaging does not ...

  7. Nacos As a configuration center , Multiple services share one dataId Configuration of

    Write it at the front This article is a review of my previous article <Spring Cloud+nacos+Feign, Implementation of registry and configuration center > A supplement to . This article briefly describes how to Nacos As configuration center . When using configuration center , We'll meet ...

  8. SpringCloud Project use Nacos As configuration center

    Reference resources :https://blog.csdn.net/qq_33619378/article/details/96991237 Nacos-server start-up Not here The new configuration stay Nacos-Serv ...

  9. nacos As configuration center

    Distributed configuration center In the microservices architecture , Why do we need a unified configuration center ? In one word, it's easy to manage , Reduce the possibility of errors . such as : Your development environment is a set of configuration , The test environment is a set of , The production environment is another set . If you modify it manually , It's inevitable ...

  10. nacos Compatible as a configuration center xml The configuration file

    Recently, the company wants to use the configuration center , Because the company uses traditional spring project , Yes springboot project , For compatibility, configuration center can be adopted , Made some attempts , After comparison, I still prefer to use nacos, Tradition dubbo use spring The way ...

Random recommendation

  1. [Xilinx]Modelsim Independent simulation Vivado Generated PLL nucleus

    EDA Tools: 1.Vivado 2015.1(64-bit) 2.Modelsim SE-64 10.1c Time: 2016.05.26 ------------------------- ...

  2. wordpress backstage 404 page

    In just ,boss Need to see the company website background , Website is used wordpress Build up , Find all 404, Fucking , therefore google, Here's the solution : location / { if (-f $request_filenam ...

  3. Use VS2013 debugging FluorineFx Program

    VS2013, establish FluorineFx Web Project approach : First new . project .Web. choice .NET 3.5 ASP.NET Form program to create a new project . Copy log.Templates.WEB-INF file ...

  4. iOS A rookie FMDB The secondary packaging is simple and easy to use

    I have nothing to write about , I hope you can correct me more ! Let's go first git download FMDB, And then put it source In folder fmdb Drag the folder into your project . Finally, you can reference the following code pair fmdb Make a simple package . This can be more intuitive ...

  5. Intellij Idea The frequently used shortcut keys

    Automatically complete the parameter definition : Ctrl+Alt+V Execution Breakpoints Expression: Alt+F8 Choose a specific method to :Shift+F7 Intelligent operation : Alt+Enter Open recent files :Ctrl+E Open recent ...

  6. WordPress Blog building and problem summary

      One .WordPress Blog building 1. install Apache web The server yum install -y httpd systemctl restart httpd systemctl enable ht ...

  7. mysql Develop basic series 2 Integer data type

    Mysql Data type of 1.  For integer types , Mysql The display width specified in parentheses after the type name is also supported , for example int(5) Indicates that the width is less than 5 Fill in the width when bit , If the specified width is not displayed, the default is int(11), General coordination zer ...

  8. Python sax modular (SAX analysis XML)

    XML Examples : <?xml version="1.0"?> <collection shelf="New Arrivals"> <m ...

  9. centos7 modify root Password mode

    1 - Start up grub menu , Select the edit option to start 2 - Press keyboard e key , To enter the editing interface 3 - find Linux 16 That line , take ro Change it to rw init=/sysroot/bin/sh 4 - Now press Co ...

  10. How to use Python manipulation Postgres database

    pip install psycopg2 psycopg2-binary #!/usr/bin/python import psycopg2conn = psycopg2.connect(databa ...