Nacos快速入门(3):整合SpringBoot实现配置管理和服务发现 - Go语言中文社区

Nacos快速入门(3):整合SpringBoot实现配置管理和服务发现


系列文章目录

Nacos快速入门(1):启动Nacos Server
Nacos快速入门(2):整合Spring
Nacos快速入门(3):整合SpringBoot
Nacos快速入门(4):整合SpringCloud
Nacos整合示例完整代码地址:https://github.com/mrKyleWang/nacos_demo

一、springboot应用接入Nacos

<!-- 1. nacos-配置管理功能依赖 -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>
<!-- 2. nacos-服务发现功能依赖 -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>

二、配置管理功能示例

示例场景:模拟用户服务获取配置中心的username属性,在getUser接口中返回

  1. 在application.properties中配置nacos server的地址
nacos.config.server-addr=127.0.0.1:8848
  1. 使用 @NacosPropertySource 加载 dataId 为 example 的配置源,并开启自动更新:
@SpringBootApplication
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosBootUserApplication {

	public static void main(String[] args) {
		SpringApplication.run(NacosBootUserApplication.class, args);
	}

}
  1. 通过 Nacos 的 @NacosValue 注解设置属性值
    示例中会加载配置中username的值,如果没有则取到的值为"null",启动自动刷新
@Controller
public class UserController {

	@NacosValue(value = "${username:null}", autoRefreshed = true)
	private String username;

	@RequestMapping(value = "/getUser")
	@ResponseBody
	public String getUser() {
		return username;
	}
}
  1. 请求getUser接口,未配置username,返回默认值null
curl -X GET "http://127.0.0.1:8082/user/getUser"
null
  1. 增加配置(两种方式示例)
    (1). Nacos管理界面添加配置
    Sample
    (2). 调用open api添加配置(注意使用Post方法请求)
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=username=zhangsan"
  1. 再次调用接口,测试发现配置已更新
curl -X GET "http://127.0.0.1:8082/user/getUser"
zhangsan

三、服务注册

示例场景:将上述用户服务注册到nacos

  1. 在application.properties中新增配置nacos.discovery.server的地址
    (注意nacos.config.server-addr和nacos.discovery.server-addr都要配置)
server.port=8082
server.servlet.context-path=/user
spring.application.name=user_service
nacos.config.server-addr=127.0.0.1:8848
nacos.discovery.server-addr=127.0.0.1:8848
  1. 使用注解@PostConstruct,在服务启动后自动向Nacos服务注册
@Configuration
public class NacosRegisterConfiguration {

	@Value("${server.port}")
	private int serverPort;

	@Value("${spring.application.name}")
	private String applicationName;

	@NacosInjected
	private NamingService namingService;

	@PostConstruct
	public void registerInstance() throws NacosException {
		namingService.registerInstance(applicationName, "127.0.0.1", serverPort, "DEFAULT");
	}
}
  1. 启动应用后,在Nacos管理界面可以看到新注册的服务实例。
    Sample
    Sample

四、服务发现/调用:

示例场景:模拟订单服务在getOrder接口中通过nacos服务发现调用user_server的getUser接口获取username,返回结果

  1. 在application.properties中配置nacos.discovery.server的地址
nacos.discovery.server-addr=127.0.0.1:8848
  1. 使用 @NacosInjected 注入 Nacos 的 NamingService 实例,并使用namingService获取提供”user_service”服务的实例,通过restTemplate调用其getUser接口
@Controller
public class OrderController {

	private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

	@NacosInjected
	private NamingService namingService;

	private RestTemplate restTemplate = new RestTemplate();

	@RequestMapping(value = "/getOrder")
	@ResponseBody
	public Map<String, Object> getOrder() {
		Map<String, Object> order = new HashMap<>();
		order.put("username", queryUserName());
		order.put("money", 100.00);
		return order;
	}

	private String queryUserName() {
		try {
			if (namingService != null) {
				// 选择user_service服务的一个健康的实例(可配置负载均衡策略)
				Instance instance = namingService.selectOneHealthyInstance("user_service");
				// 拼接请求接口url并请求选取的实例
				String url = "http://" + instance.getIp() + ":" + instance.getPort() + "/user/getUser";
				ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
				return entity.getBody();
			}
		} catch (Exception e) {
			logger.error("query user error", e);
		}
		return null;
	}
}
  1. 调用订单服务的getOrder接口,返回正确结果
curl -X GET "http://127.0.0.1:8081/order/getOrder"
{"money":100.0,"username":"zhangsan"}
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wk52525/article/details/88146854
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢