Java之SpringCloud nocos註冊中心講解

一、nacos是什麼?

Nacos是用來發現、配置和管理微服務。Nacos提供瞭一組簡單易用的特性集,幫助快速實現動態服務發現服務配置、服務元數據流量管理

二、使用步驟

1.安裝nacos 服務器

直接運行 startup.cmd 訪問 localhost:8848/nacos
初始密碼 nacos nacos

在這裡插入圖片描述

2.導入依賴和配置yaml

在這裡插入圖片描述

父項目依賴pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.csdn</groupId>
    <artifactId>springcloud_nacos</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springcloud_share_6002</module>
        <module>springcloud_user_6001</module>
        <module>springcloud_common</module>
    </modules>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <lombok.version>1.18.16</lombok.version>
        <log4j.version>1.2.17</log4j.version>
        <logback-core.version>1.2.3</logback-core.version>
        <mysql-connector-java.version>8.0.21</mysql-connector-java.version>
        <druid.version>1.1.23</druid.version>
        <mybatis-spring-boot-starter.version>2.1.4</mybatis-spring-boot-starter.version>
        <spring-boot-dependencies.version>2.3.8.RELEASE</spring-boot-dependencies.version>
        <spring-cloud-dependencies.version>Hoxton.SR9</spring-cloud-dependencies.version>
        <spring-cloud-alibaba.version>2.2.3.RELEASE</spring-cloud-alibaba.version>
        <swagger.version>2.7.0</swagger.version>
        <pagehelper.version>1.2.3</pagehelper.version>
        <jodatime.version>2.10.1</jodatime.version>
        <jjwt.version>0.10.7</jjwt.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!--很重要的包:springcloud的依賴-->
            <!-- <scope>import</scope>解決單繼承問題,類似parent標簽, -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring-cloud-alibaba-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--springboot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--數據庫-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-java.version}</version>
            </dependency>
            <!--數據源-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <!--mybatis的springboot啟動器-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-spring-boot-starter.version}</version>
            </dependency>
            <!--日志測試-->
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
            <!--log4j-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>${logback-core.version}</version>
            </dependency>
            <!--swagger-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>${swagger.version}</version>
            </dependency>
            <!--swagger ui-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>${swagger.version}</version>
            </dependency>
            <!--druid alibaba-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>${pagehelper.version}</version>
            </dependency>
            <!--日期時間工具-->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>${jodatime.version}</version>
            </dependency>

            <!-- JWT -->
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-api</artifactId>
                <version>${jjwt.version}</version>
            </dependency>
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-impl</artifactId>
                <version>${jjwt.version}</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-jackson</artifactId>
                <version>${jjwt.version}</version>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <!--打包插件-->
    </build>
</project>

在需要被nacos發現的微服務個module加上nacos依賴

<!--服務註冊-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

springcloud_common的pom依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud_nacos</artifactId>
        <groupId>com.csdn</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud_common</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <!--spring默認使用yml中的配置,但有時候要用傳統的xml或properties配置,就需要使用spring-boot-configuration-processor瞭-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <!--服務註冊-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--服務容錯-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- JWT -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

在這裡插入圖片描述

@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**
     * 定義接口的總體信息
     *
     * @return
     */
    private ApiInfo webApiInfo() {

        return new ApiInfoBuilder()
                .title("Swagger API 文檔")
                .description("即使再小的帆也能遠航")
                .version("1.0")
                .contact(new Contact("liar", "http://www.jsxllht.com", "**********[email protected]"))
                .build();
    }

    private ApiInfo adminApiInfo() {

        return new ApiInfoBuilder()
                .title("Swagger Admin 文檔")
                .description("即使再小的帆也能遠航")
                .version("1.0")
                .contact(new Contact("liar", "http://www.jsxllht.com", "**********[email protected]"))
                .build();
    }

    @Bean
    public Docket webApiConfig() {

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi") // 用戶組
                .apiInfo(webApiInfo()) // 組的信息
                .select()
                //隻顯示api路徑下的頁面
                .paths(Predicates.and(PathSelectors.regex("/api/.*")))  // 用戶接口的判斷
                .build();

    }

    @Bean
    public Docket adminApiConfig() {

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi") // 管路⚪組
                .apiInfo(adminApiInfo()) // 組的信息
                .select()
                //隻顯示admin路徑下的頁面
                .paths(Predicates.and(PathSelectors.regex("/admin/.*")))
                .build();

    }
}
/**
 *  業務異常類
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AppException extends RuntimeException{

    private String code;
    private String message;

    public AppException(ResponseEnum responseEnum){
        this.code = responseEnum.getCode();
        this.message = responseEnum.getMessage();
    }
}
// 這是一個controller 的增強類【專門在controller 拋出異常的時候  增強】
@ControllerAdvice
public class ControllerExceptionAdvice {

    /**
     *  如果拋出的是 AppException 的增強
     *  返回值 就是返回的頁面
     *  參數: controller 拋出的異常
     */
    @ExceptionHandler(AppException.class)
    @ResponseBody
    public R appExceptionHandler(AppException ex, HttpServletRequest request){
       return new R(ex.getCode(),ex.getMessage(),null);
    }

    /**
     *  如果拋出的是Exception 的增強
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception ex, HttpServletRequest request){
        ex.printStackTrace();
        return new R(ResponseEnum.SYSTEM_ERROR,null);
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
// 創建統一的返回格式
public class R<T> {

    private String code;
    private String message;
    private T data;

    public R(ResponseEnum responseEnum, T data) {
        this.code = responseEnum.getCode();
        this.message = responseEnum.getMessage();
        this.data = data;
    }
}
public enum ResponseEnum {
    SUCCESS("200","成功003"),
    USERNAME_NOT_FOUND("300","用戶名不存在"),
    USERNAME_OR_PASSWORD_INVALIDATE("301","用戶名或者密碼錯誤"),
    ROLE_NO_MENUS("302","此角色沒有任何菜單權限,請盡早分配"),
    HAS_NO_TOKEN("303","還沒有登錄"),
    TOKEN_ERROR("304","別想試圖偽造令牌"),
    TOKEN_TIMEOUT("305","對不起登錄狀態已經失效,請重新登錄"),
    HAS_NO_RIGHT("306","權限不足"),
    SYSTEM_ERROR("500","發生未知異常。。。"),
    FEIGN_BSUY("307","系統正忙,稍後再試。。"),
    FLOW_BLOCK("308","流量被限制瞭,請稍後再使"),
    DEG_BLOCK("309","系統很忙,稍後再試。。。"),
    SMS_ERROR("310","短信發送失敗,請稍後再試。。。"),
    SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL("311","發送短信太頻繁,過會再發。。。"),
    CODE_ERROR("312","驗證碼錯誤請重試"),
    CODE_EXCPTION("313","驗證碼超時"),
    ACCOUNT_NO_EXISTS("314","用戶不存在"),
    STATUS_BE_MODIFIED("315","用戶已被審核")
    ;
    private String code;
    private String message;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    ResponseEnum(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

springcloud_user_6001的yaml(在註冊中心服務的名字 不能一樣)

server:
  port: 6001
#數據源
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/hub_user_center?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456
      initial-size: 10
      max-active: 50
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # mysql 數據庫的特征  會關閉已經連接瞭8個小時的連接
      validation-query: SELECT 1 FROM DUAL
  application:
    name: user-6001
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
# mybatis 配置
mybatis:
  # 掃描映射文件
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # 開啟駝峰映射配置
    map-underscore-to-camel-case: true
# log
# 整個工程隻答應info 以及以上級別的日志
logging:
  level:
    root: info
    com.csqf.mapper: debug																									

springcloud_share_6002的yaml(在註冊中心服務的名字 不能一樣)

server:
  port: 6002
#數據源
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/hub_share_center?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456
      initial-size: 10
      max-active: 50
      min-idle: 10
      max-wait: 60000
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # mysql 數據庫的特征  會關閉已經連接瞭8個小時的連接
      validation-query: SELECT 1 FROM DUAL
  application:
    name: share-6002
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
# mybatis 配置
mybatis:
  # 掃描映射文件
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # 開啟駝峰映射配置
    map-underscore-to-camel-case: true
# log
# 整個工程隻答應info 以及以上級別的日志
logging:
  level:
    root: info
    com.csqf.mapper: debug

2.RestTemplate

RestTemplate是Spring Resources中一個訪問第三方RESTful API接口的網絡請求框架。RestTemplate的設計原則和其他Spring Template(例如JdbcTemplate、JmsTemplate)類!,都是為執行復雜任務提供瞭一個具有默認行為的簡單方法。

設置RestTemplate為Bean

在這裡插入圖片描述

springcloud_user_6001中寫一個查詢方法代碼如下(示例):

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getUserById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if ("".equals(user)){
            return "";
        }
        return user.getUserName();
    }
}

在springcloud_share_6002寫一個DTO(示例):
繼承Share實力類,加上user中返回的userName

@Data
public class ShareDto extends Share {
    private String userName;
}

在springcloud_share_6002中使用RestTemplate調用user並得到userName

@RestController
@RequestMapping("/api/share")
public class ShareContoller {
    @Autowired
    private ShareServiceImpl shareService;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/{id}")
    public R getShareById(@PathVariable("id") Integer id){
        Share share = shareService.getShareById(id);
       R r = restTemplate.getForObject("http://localhost:6001/api/user/" + share.getUserId(), R.class);
        String s = r.getData().toString();
        ShareDto shareDto = new ShareDto();
        BeanUtils.copyProperties(share,shareDto);
        shareDto.setUserName(s);
        return new R(ResponseEnum.SUCCESS,shareDto);
    }
}

最後訪問swagger(http://localhost:6002/swagger-ui.html)測試得到dto實體類中的對象

總結

nacos的作用就是一個註冊中心,用來管理註冊上來的各個微服務。

到此這篇關於Java之SpringCloud nocos註冊中心講解的文章就介紹到這瞭,更多相關Java之SpringCloud nocos內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: