java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java之SpringCloud nocos

Java之SpringCloud nocos注册中心讲解

作者:深情以改

这篇文章主要介绍了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", "**********6@qq.com"))
                .build();
    }

    private ApiInfo adminApiInfo() {

        return new ApiInfoBuilder()
                .title("Swagger Admin 文档")
                .description("即使再小的帆也能远航")
                .version("1.0")
                .contact(new Contact("liar", "http://www.jsxllht.com", "**********6@qq.co"))
                .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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文