用SpringCloud Alibaba搭建属于自己的微服务(十二)~基础搭建~alibaba nacos的服务注册和发现

一.概述

在第十一章节,我们已经安装了nacos的服务端,本章节把我们的微服务注册到nacos上面.

二.服务注册和发现

1.ccm-mall.pom中有了springcloud-alibaba的版本管理依赖,子工程中实际引入时无需再声明依赖版本号.


<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-alibaba-dependenciesartifactId>
    <version>2.1.2.RELEASEversion>
    <type>pomtype>
    <scope>importscope>
dependency>

2.server.pom中实际引入nacos客户端的maven依赖.

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>

3.yml配置文件.

配置文件中增加spring.cloud.nacos相关配置,根据实际信息填入

server:
  port: 1002  #服务端口
spring:
  application:
    name: server-user #服务名称
  datasource:
    username: root
    password: Test2016@
    url: jdbc:mysql://47.96.131.15:3306/user?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true
    type: com.alibaba.druid.pool.DruidDataSource
  cloud:
    nacos:
      discovery:
        server-addr: 47.96.131.1811:8848
mybatis-plus:
  typeAliasesPackage: com.ccm.server.user.dao.mysql.domain  #数据库实体类包
  mapper-locations: classpath:mappering/*.xml #xml文件扫描

3.服务启动类加上@EnableDiscoveryClient注解,表示开启服务注册和发现.

package com.ccm.server.user;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 *  @Description server-user服务启动类
 *  @Author zhouzhiwu
 *  @CreateTime 2020/07/03 14:04
 */
@EnableDiscoveryClient //注册中心客户端
@ComponentScan(basePackages = "com.ccm")
@EnableSwagger2
@MapperScan(basePackages = "com.ccm.server.user.dao.mysql.mapper")
@SpringBootApplication //声明为一个启动类
@Import(value = PaginationInterceptor.class)
public class ServerUserApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServerUserApplication.class,args);
    }
}

4.启动微服务.

用SpringCloud Alibaba搭建属于自己的微服务(十二)~基础搭建~alibaba nacos的服务注册和发现_第1张图片

5.查看nacos,检查服务是否已经注册上去.

用SpringCloud Alibaba搭建属于自己的微服务(十二)~基础搭建~alibaba nacos的服务注册和发现_第2张图片
源码地址:https://gitee.com/chouchimoo/ccm-mall.git(本章节分支:zj-12)

你可能感兴趣的:(nacos,alibaba,springcloud,spring,java,spring,boot)