Quick Start for Nacos Spring Projects
This quick start introduces how to enable Nacos configuration management and service discovery features for your Spring project.
For more details about Nacos Spring Boot: nacos-spring-project.
The quick start includes two samples:
- How to enable Nacos server and Nacos Spring configuration modules to implement dynamic configuration management;
- How to enable Nacos server and Nacos Spring service discovery modules to implement service registration and discovery.
Prerequisite
Follow instructions in Nacos Quick Start to download Nacos and start the Nacos server.
Enable Configuration Service
Once you start the Nacos server, you can follow the steps below to enable the Nacos configuration management service for your Spring project.
Sample project: nacos-spring-config-example
- Add the Nacos Spring dependency.
The the latest version can be available in maven repositories such as “mvnrepository.com”.
- Add the
@EnableNacosConfig
annotation to enable the configuration service. In the code below,@NacosPropertySource
is used to load the configuration source whosedataId
isexample
, and autorefresh is also enabled:
- Specify the property value for the
@NacosValue
annotation of Nacos.
-
Start Tomcat and call
curl http://localhost:8080/config/get
to get configuration information. Because no configuration has been published, afalse
message is returned. -
Now you can call Nacos Open API to publish a configruation to the Nacos server. Assume the dataId is
example
, and content isuseLocalCache=true
.
- Access
http://localhost:8080/config/get
again, and you get a return message oftrue
, indicating that the value ofuseLocalCache
in your application has been updated.
Enable Service Discovery
Now you would like to enable the service discovery function of Nacos in your Spring project.
Sampe project: nacos-spring-discovery-example
- Add the Nacos Spring dependency.
The the latest version can be available in maven repositories such as “mvnrepository.com”.
- Add the
@EnableNacosDiscovery
annotation to enable the service discovery function of Nacos:
- Use
@NacosInjected
to inject a NacosNamingService
instance:
-
Start Tomcat and call
curl http://localhost:8080/discovery/get?serviceName=example
, and the return value is an empty JSON array[]
. -
Call Nacos Open API to register a service called
example
to the Nacos Server.
- Access
curl http://localhost:8080/discovery/get?serviceName=example
again, and you will get the following return: