Quick Start for Nacos Spring Boot Projects
This quick start introduces how to enable Nacos configuration management and service discovery features for your Spring Boot project.
For more details about Nacos Spring Boot: nacos-spring-boot-project.
The quick start includes two samples:
- How to enable dynamic configuration updates with Nacos server and nacos-config-spring-boot-starter;
- How to enable service registration and discovery with Nacos Server and nacos-discovery-spring-boot-starter.
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 Boot project.
Sample project: nacos-spring-boot-config-example
- Add the Nacos Spring Boot dependency.
Note: Version 0.2.x.RELEASE is compatible with the Spring Boot 2.0.x line. Version 0.1.x.RELEASE is compatible with the Spring Boot 1.x line.
- Configure the Nacos server address in
application.properties
:
- Use
@NacosPropertySource
to load the configuration source whosedataId
isexample
, and enable autorefresh of configuration updates:
- Specify the property value of the
@NacosValue
annotation of Nacos.
-
Start
NacosConfigApplication
and callcurl http://localhost:8080/config/get
. You will get a return message offalse
, as no configuration has been published so far. -
Call Nacos Open API to publish a configuration to the Nacos server. Assume the dataId is
example
, and the content isuseLocalCache=true
.
- Access
http://localhost:8080/config/get
again, and the returned value will betrue
,indicating that the value ofuseLocalCache
in your application has been updated.
Enable Service Discovery
Now you would also like to enable the service discovery feature of Nacos in your Spring Boot project.
Sample project: nacos-spring-boot-discovery-example
- Add the Nacos Spring Boot dependency.
Note: Version 0.2.x.RELEASE is compatible with the Spring Boot 2.0.x line. Version 0.1.x.RELEASE is compatible with the Spring Boot 1.x line.
- Configure the Nacos server address in
application.properties
:
- Use
@NacosInjected
to inject a NacosNamingService
instance:
-
Start
NacosDiscoveryApplication
and callcurl http://localhost:8080/discovery/get?serviceName=example
,you will get a return value of 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: