Nacos ECO Project for Spring Framework
Nacos is an open source project for discovering, configuring and managing cloud-native applications. Key features of Nacos include:
Nacos Spring Project, which is based on Nacos, fully embraces the Spring ecosystem and is designed to help you build Spring applications rapidly.
The project contains a core module named nacos-spring-context. It enables you to expand modern Java programming models in the following ways:
These features strongly depend on Spring Framework 3.2+ API, and can be seamlessly integrated with any Spring Stack, such as Spring Boot and Spring Cloud.
Note: We recommend that you use annotation-driven programming, even though XML-based features also work.
@NacosPropertiesIncluded in this section are some samples for you to get a quick start with Nacos Spring.
Take the Spring Web MVC project for example:
Check out the source code of nacos-spring-project :
$ git clone [email protected]:nacos-group/nacos-spring-project.git
Build your source code with Maven:
$ mvn clean package
Run Spring Web MVC Samples:
$ java -jar target/nacos-spring-webmvc-sample.war
The following table shows the dependencies and compatabilities of Nacos Spring Project.
| Dependencies | Compatibility |
|---|---|
| Java | 1.8+ |
| Spring Context | 3.2+ |
| Alibaba Spring Context Support | 1.0.1+ |
| Alibaba Nacos | 1.1.1+ |
This quickstart shows you how to enable Nacos and its service discovery and configuration management features in your Spring project.
Before you configure your Spring project to use Nacos, you need to start a Nacos server in the backend. Refer to Nacos Quick Start for instructions on how to start a Nacos server.
Complete the following steps to enable Nacos for your Spring project.
Add nacos-spring-context in your Spring application's dependencies:
...
com.alibaba.nacos
nacos-spring-context
1.1.0
...
Note: Support Spring 5 from version 0.2.3-RC1, support Spring 6 from version 2.1.0.
Add the @EnableNacos annotation in the @Configuration class of Spring and specify "${host}:${port}" of your Nacos server in the serverAddr attribute:
@Configuration
@EnableNacos(
globalProperties =
@NacosProperties(serverAddr = "${nacos.server-addr:localhost:12345}")
)
public class NacosConfiguration {
...
}Now you would like to use the confguration service of Nacos. Simply use Dependency Injection to inject ConfigService instance in your Spring Beans when @EnableNacos is annotated, as shown below:
@Service
public class ConfigServiceDemo {
@NacosInjected
private ConfigService configService;
public void demoGetConfig() {
try {
String dataId = "{dataId}";
String group = "{group}";
String content = configService.getConfig(dataId, groupId, 5000);
System.out.println(content);
} catch (NacosException e) {
e.printStackTrace();
}
}
...
}ConfigService is the key interface of Nacos which helps you to get or publish configurations.
The following code achieves the same effect:
…If you would also like to use the service discovery feature of Nacos, you can inject a NamingService instance for service discovery:
@NacosInjected
private NamingService namingService;For details about the usages of ConfigService and NamingService, please refer to Nacos SDK.
This section provides a detailed description of the key features of nacos-spring-context:
@EnableNacos is a modular-driven annotation that enables all features of Nacos Spring, including Service Discovery and Distributed Configuration. It equals to @EnableNacosDiscovery and
@EnableNacosConfig, which can be configured separately and used in different scenarios.
Suppose there was a config in Nacos Server whose dataId is "testDataId" and groupId is default group("DEFAULT_GROUP"). Now you would like to change its content by using the ConfigService#publishConfig method:
@NacosInjected
private ConfigService configService;
@Test
public void testPublishConfig() throws NacosException {
configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527");
}Then you would like to add a listener, which will be listening for the config changes. You can do this by adding a config change listener method into your Spring Beans:
@NacosConfigListener(dataId = DATA_ID)
public void onMessage(String config) {
assertEquals("mercyblitz", config); // asserts true
}The code below has the same effect:
configService.addListener(DATA_ID, DEFAULT_GROUP, new AbstractListener() {
@Override
public void receiveConfigInfo(String config) {
assertEquals("9527", config); // asserts true
}
});Note: @NacosConfigListener supports richer type conversions.
The type conversion of @NacosConfigListener includes both build-in and customized implementations. By default, build-in type conversion is based on Spring DefaultFormattingConversionService, which means it covers most of the general cases as well as the rich features of the higher Spring framework.
For example, the content "9527" in the preceding example can also be listened by a method with integer or the Integer argument:
@NacosConfigListener(dataId = DATA_ID)
public void onInteger(Integer value) {
assertEquals(Integer.valueOf(9527), value); // asserts true
}
@NacosConfigListener(dataId = DATA_ID)
public void onInt(int value) {
assertEquals(9527, value); // asserts true
}Of course, nacos-spring-context provides elastic extension for developers. If you define a named nacosConfigConversionService Spring Bean whose type is ConversionService , the DefaultFormattingConversionService will be ignored. In addition, you can customize the implementation of the NacosConfigConverter interface to specify a listener method for type conversion:
public class UserNacosConfigConverter implements NacosConfigConverter {
@Override
public boolean canConvert(Class targetType) {
return true;
}
@Override
public User convert(String source) {
return JSON.parseObject(source, User.class);
}
}The UserNacosConfigConverter class binds the @NacosConfigListener.converter() attribute:
@NacosInjected
private ConfigService configService;
@Test
public void testPublishUser() throws NacosException {
configService.publishConfig("user", DEFAULT_GROUP, "{\"id\":1,\"name\":\"mercyblitz\"}");
}
@NacosConfigListener(dataId = "user", converter = UserNacosConfigConverter.class)
public void onUser(User user) {
assertEquals(Long.valueOf(1L), user.getId());
assertEquals("mercyblitz", user.getName());
}By default, starting from version 1.1.2
No open issues yet, or sync has not completed.