The springboot project uses Nacos as the configuration center

Bamboo wind is a little sweet 2022-02-13 07:45:23 阅读数:171

springboot project uses nacos configuration

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

copyright:author[Bamboo wind is a little sweet],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130745194331.html