consul教程:springboot服务注册与发现(2)-服务提供者notice 作者:马育民 • 2021-01-23 11:18 • 阅读:10049 # 介绍 notice服务用于向移动端发送通知,即:下图中的 【推送消息微服务】 [![](https://www.malaoshi.top/upload/pic/consul/QQ20210123110925.png)](https://www.malaoshi.top/upload/pic/consul/QQ20210123110925.png) ### 工程下载 本工程: https://gitee.com/65242847/springcloud_consul/tree/master/notice_consul 所有工程: https://gitee.com/65242847/springcloud_consul ### spring-cloud-consul 官网 https://spring.io/projects/spring-cloud-consul ### 功能说明 - 启动服务时,向consul注册自己 - 提供2个http接口,供其他微服务调用 - `/sendNotice`:发送消息 - `/getNoticeById`:根据id获取发送的消息 ### 搭建说明 - 基础工程是:springboot+mybatis,使用druid连接池,需要mysql数据库 - 添加springcloud依赖 - 添加consul依赖 - 在application.yml添加consul配置 ### 工程结构图 [![](https://www.malaoshi.top/upload/pic/consul/QQ20210123131430.png)](https://www.malaoshi.top/upload/pic/consul/QQ20210123131430.png) # mysql 创建表: ``` CREATE TABLE `t_notice` ( `id` VARCHAR(32) NOT NULL, `from_userid` VARCHAR(32) NULL DEFAULT NULL, `to_userid` VARCHAR(32) NULL DEFAULT NULL, `msg` VARCHAR(128) NULL DEFAULT NULL COLLATE 'utf8mb4_unicode_ci', PRIMARY KEY (`id`) ) COMMENT='推送消息日志' COLLATE='latin1_swedish_ci' ENGINE=InnoDB ; ``` # 创建springboot工程 https://www.malaoshi.top/show_1EF5qXjMmlZR.html # pom.xml consul注册依赖 ``` org.springframework.cloud spring-cloud-starter-consul-discovery ``` # application.yml ### consul注册配置 ``` spring: #consul注册中心配置 cloud: consul: host: localhost # consul服务的ip port: 8500 # consul服务的port discovery: serice-name: ${spring.application.name} # 注册到consul的服务名 deregister: true # 服务停止时取消注册 # 健康检查的接口,默认为 /actuator/health,由 Spring Boot Actuator 提供 health-check-path: /actuator/health application: name: notice-service # 服务名字 ``` # 接口 ums服务调用该接口,传递的数据是json格式,所以此处要用@ `RequestBody` 注解 ``` //url后面没有/,client发请求时有没有/都可以。如果这里有/,那么client发请求时必须带上/ @PostMapping(value="/sendNotice") //ums服务调用该接口,传递的数据是json格式,所以此处要用@RequestBody注解 public JsonResult sendNotice(@RequestBody Notice notice){ noticeService.sendNotice(notice); return new JsonResult(200,"成功!"); } ``` 原文出处:http://malaoshi.top/show_1IXSTP1shap.html