Nacos serves as the registry and configuration center
Install Nacos
See the website
After installing the Nacos 127.0.0.1 is access address: 8848 / Nacos/index. HTML
The default login name and password are both nacOS
Use Nacos as the registry
For myself, THE version I used here is Boot 2.3.2.RELEASE and Spring Cloud Alibaba 2.2.5.RELEASE
<! -- Here are the dependencies I introduced -->
<! Registry dependencies, service registration and discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.5. RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code
Then add the annotation @enableDiscoveryClient to the entry class to register and discover the service.
/** * Enable service registration and discovery in Spring Cloud */
@EnableDiscoveryClient
@SpringBootApplication
@RestController
public class NacosServerApplication {
public static void main(String[] args) {
SpringApplication.run(NacosServerApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return "Hello "+ name; }}Copy the code
The registry address and the name of the service registered to the registry are configured in the configuration file application.yml
server:
port: 7001
The name of the service registered to the registry
spring:
application:
name: nacos-server
# NACOS Registry address
cloud:
nacos:
discovery:
server-addr: 127.0. 01.: 8848
Copy the code
Go to the Nacos registry after startup and you can see that the configured service is registered with the registry
This section describes the consumption modes of the three services
RPC calls are not introduced here, but RestTemplate provided by Spring, WebClient, and Feign packaged by Netflix are introduced respectively.
RestTemplate way
First, create a new service to invoke the nacOS-server service. The new service is named nacos-client-common and has the same configuration as nacOS-server
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosClientCommonApplication {
// Requires @autowired injection
@Autowired
private RestTemplate restTemplate;
/** * 2. Spring Cloud has made enhancements to RestTemplate to simplify the previous invocation * with a little configuration@return* /
@GetMapping("/test1")
public String test1(a) {
return restTemplate.getForObject("http://nacos-server/hello? name=kangkang", String.class);
}
/** * Added when defining the RestTemplate@LoadBalancedNote, and in the real call to the service interface, the original host part is by manual stitching IP and port, * directly use the service name to write the request path can be. When the actual call is made, Spring Cloud intercepts the request, selects the node through the load balancer, and replaces the service name part with a specific IP address and port, thus implementing load balancing calls based on the service name. *@return* /
@Bean
@LoadBalanced
public RestTemplate restTemplate(a) {
return newRestTemplate(); }}Copy the code
WebClient way
WebClient is Spring5 responsive programming’s way of invoking services like RestTemplate
Need to introduce dependencies to support reactive programming<! Support WebClient to call service instead of RestTemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Copy the code
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosClientCommonApplication {
@Autowired
private WebClient.Builder webClientBuilder;
/** * RestTemplate and WebClient are both spring-packaged tools *@return* /
@GetMapping("/test2")
public Mono<String> test2(a) {
return webClientBuilder.build()
.get()
.uri("http://nacos-server/hello? name=yunqing")
.retrieve()
.bodyToMono(String.class);
}
/** * Rely on Spring-boot-starter-webflux * WebClient is a recent addition to Spring 5 and can be thought of as a reactive version of RestTemplate. *@return* /
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder(a) {
returnWebClient.builder(); }}Copy the code
Feign way
<! -- Introducing dependencies -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.6. RELEASE</version>
</dependency>
Copy the code
// Add the following annotation to start scanning FeignClient
@EnableFeignClients
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class NacosClientCommonApplication {
// Inject the interface of the service. The interface of the service needs to be declared in the project of the service, which is still implemented in nacos-server
@Autowired
private FeignService feignService;
/** * Rely on spring-cloud-starter-openFeign **@return* /
@GetMapping("/test3")
public String test3(a) {
return feignService.hello("spring cloud"); }}Copy the code
Service interface FeignServer
// The annotation specifies the name of the service that this interface calls
@FeignClient("nacos-server")
public interface FeignService {
@GetMapping("/hello")
String hello(@RequestParam String name);
}
Copy the code
Nacos serves as the configuration center
Creating a namespace
You first need to add two new namespaces in Nacos, and then add the corresponding configuration to each namespace after dev and test.
As shown in the figure, there is also a reserved space, public, which exists by default. Next you can see three namespaces in the configuration Management configuration list. As shown in the figure below, I created a configuration in the dev namespace.
How do I locate a configuration
- First of all by
Namespace namespace
The namespace ID must be used to locate the configuration of the namespace. If the namespace id is not configured, it is used by defaultpublic
The namespace The prefix prefix
If the name is not specified, the default value is the current service name, which is also the current service nameThe suffix file - the extension
The configuration suffix is determined. The default isproperties
Because of my configurationData Id
Created asyaml
Format namenacos-config.yaml
So the suffix here needs to beyaml
Group group
Determines the configured group name, the default group nameDEFAULT_GROUP
- Also through
spring.profile.active
orgroup
Configure multiple environments, but it is recommendednamespace
- bootstrap.yml
Yml or bootstrap.properties must be used for this configuration
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
file-extension: yaml Nacos-config. yaml is the application name plus the file extension. The default value is properties
group: DEFAULT_GROUP # Default GROUP, such as dev-group test-group
prefix: ${spring.application.name} The default prefix is the name of the application
namespace: 87d915fc-e1be-4d0e-8dbd-d3314ac47844 # namespaces
server:
port: 7007
Copy the code
What exactly is configured?
A Kangqing.title is actually configured
Reading Configuration Details
The purpose of reading the configuration is to prove that the configuration added through the configuration center can take effect in the application
<! -- This is the dependency of configuration center -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.5. RELEASE</version>
</dependency>
Copy the code
/** * As you can see, nacOS's service discovery module is not included in this example, so the two contents are completely independent of the ** annotation@RefreshScopeIt is used to enable dynamic refreshing of the configuration content in this class, which will also take effect immediately after our application is launched. * /
@RefreshScope
@RestController
@SpringBootApplication
public class NacosConfigApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigApplication.class, args);
}
/** ** Note that the colon cannot be omitted */
@Value("${kangqing.title:}")
private String title;
@GetMapping("/test")
public String hello(a) {
return "result -> "+ title; }}Copy the code
Multi-configuration loading
For example, I have already loaded the nacos-config.yaml configuration, and I don’t want to put all the configuration into this one file, so I add mybatis-plus.yaml configuration to nacos to load multiple configurations in the application
A:
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
namespace: 535d5ae5-de1e-443b-a0a7-68a34e52946d
ext_config[0]:
data-id: nacos-config.yaml
group: DEFAULT_GROUP
refresh: true
ext_config[1]:
data-id: mybatis-plus.yaml
group: DEFAULT_GROUP
refresh: true
Copy the code
Method 2:
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: 127.0. 01.: 8848
namespace: 535d5ae5-de1e-443b-a0a7-68a34e52946d
shared-configs:
- nacos-config.yaml
- mybatis-plus.yaml
refresh-enabled: true
Copy the code
Since there are multiple configuration modes, the prefix suffix group has the highest priority, followed by mode 1, and then mode 2. That is, mode 2 will be overwritten by mode 1, and mode 2 will be overwritten by the prefix suffix group.
- Note: The above knowledge points are summarized based on the stand-alone VERSION of NACOS. They are not applicable to the production environment. Please deploy NACOS cluster and NACOS data persistence separately in the production environment.