(四)springcloud之Nacos注册服务与发现-1

news2024/11/23 12:13:16

前言:一段时间来忙忙碌碌,回头发现很多技术已经更新了很多,很长一段时间都在忙其他的事情,以至于没有太多关注于微服务更新,今天更新了下版本以便于后期使用,突然发现很多东西已经被删除或直接改变了,…。
版本:
springboot:2.7.6
springcloud:2021.0.5
spring-cloud-alibaba-dependencies:2021.0.1.0
nacos:2.1.2
为了更为真实的模拟开发环境,这里将分为以下模块:
1.父工程(管理版本)
2.公共模块:Common-API
3.服务提供者:NacosClientProvider8001,NacosClientProvider8001(为了测试负载均衡这里准备两个模块,当让准备一个模块也可以,使用idea虚拟一个模块也可以)
4.服务消费者:NacosClientConsumer80

(一)父工程

此模块只为了版本控制,所以只有pom.xml文件

<?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.qwy</groupId>
    <artifactId>springcloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Common-API</module>
        <module>NacosClientProvider8001</module>
        <module>NacosClientProvider8002</module>
        <module>NacosClientConsumer80</module>
    </modules>
    <!--表明是父工程-->
    <packaging>pom</packaging>

    <!-- 统一管理jar包版本 -->
    <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>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
        <mysql.version>5.1.47</mysql.version>
        <druid.version>1.1.16</druid.version>
        <mybatis.spring.boot.version>2.2.2</mybatis.spring.boot.version>
        <mybatis.plus.boot.version>3.5.2</mybatis.plus.boot.version>
    </properties>

    <!-- 子模块继承之后,提供作用:锁定版本+子modlue不用写groupId和version  -->
    <dependencyManagement>
        <dependencies>
           <!-- <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-loadbalancer</artifactId>
                <version>2.7.6</version>
            </dependency>-->
            <!--spring boot 2.7.6-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud 2021.0.5-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba 2021.0.1.0-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.0.1.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>2.0.20</version>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis.plus.boot.version}</version>
            </dependency>

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis.spring.boot.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
                <optional>true</optional>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

此配置中引入对了albaba的依赖:

             <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

(二)公共模块Common-API

1.pom.xml配置

<?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</artifactId>
        <groupId>com.qwy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Common-API</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>

</project>

2.配置公共的bean

此类主要为了一般对应数据库中的字段

a.Users.java

package com.qwy.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @Author:齐
 * @Package:com.qwy.bean
 * @Project:springcloud1
 * @name:Users
 * @Date:2022/12/11 2:33
 * @Filename:Users
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_user")
public class Users {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    @TableField(exist = false)
    private Integer age;
    @TableField(exist = false)
    private Date birthday;
    private String address;
}

此类主要为了一般对应数据库中的字段

b.Order.java

package com.qwy.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @Author:齐
 * @Package:com.qwy.bean
 * @Project:springcloud1
 * @name:Orders
 * @Date:2022/12/11 3:52
 * @Filename:Orders
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_order")
public class Orders {
    @TableId(type = IdType.AUTO)
    private Long id;
    @TableField(exist = false)
    private Date createTime;
    @TableField(value = "user_id")
    private Long usersId;
    private String name;
    private Long price;
    private Integer num;
}

此类主要为了对POJO进行扩展,以便以后封装条件或对数据库查询出的数据进行综合封装等作用

c.ExtendsOrder.java

package com.qwy.bean;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author:齐
 * @Package:com.qwy.bean
 * @Project:springcloud1
 * @name:ExtendsOrders
 * @Date:2022/12/11 4:06
 * @Filename:ExtendsOrders
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExtendsOrders extends Orders {
    @TableField(exist = false)
    private Users users;
}

d.Code.java

此类主要封装以后Controler响应的状态码,以便和前端程序员进行友好的交互

package com.qwy.bean;
public class Code {
    public  static final Integer SAVE_OK=20021;
    public  static final Integer DELETE_OK=20022;
    public  static final Integer UPDATE_OK=20023;
    public  static final Integer SELECT_OK=20024;

    public  static final Integer SAVE_ERR=20011;
    public  static final Integer DELETE_ERR=20012;
    public  static final Integer UPDATE_ERR=20013;
    public  static final Integer SELECT_ERR=20014;

    public  static final Integer SYSTEM_ERR=20031;
    public  static final Integer BUSINESS_ERR=20032;
    public  static final Integer UNKNOWN_ERR=20033;

}

e.CommonResult.java

此类主要封装以后Controller返回的数据。

package com.qwy.bean;

/**
 * @Author:齐
 * @Package:com.qwy.bean
 * @Project:springcloud1
 * @name:CommonResult
 * @Date:2022/12/11 2:36
 * @Filename:CommonResult
 */
public class CommonResult<T> {
    private Integer code;
    private T data;
    private String message;

    public CommonResult() {
    }

    public CommonResult(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    public CommonResult(Integer code,T  data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

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

    public Object getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

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

}

3.公共的异常处理类

a.BusinessException.java

此类主要处理用户业务异常处理。

package com.qwy.exception;


/**
 * 定义业务异常处理类
 */

public class BusinessException extends RuntimeException {
    private Integer code;

    public BusinessException(Integer code) {
        this.code = code;
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code=code;
    }

    public BusinessException(Integer code, String message, Throwable cause) {
        super(message, cause);
        this.code=code;
    }
}

b.SystemException.java

此类主要处理一些系统异常

package com.qwy.exception;

/**
 * 定义系统异常处理类
 */

public class SystemException extends RuntimeException {
    private Integer code;

    public SystemException( Integer code) {

        this.code = code;
    }

    public SystemException(Integer code, String message) {
        super(message);
        this.code=code;
    }

    public SystemException(Integer code,String message, Throwable cause) {
        super(message, cause);
        this.code=code;
    }
}

c.ExceptionResultAdvice.java

此次处理Controller处理异常的返回。

package com.qwy.exception;

import com.qwy.bean.Code;
import com.qwy.bean.CommonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice//该注解表明该类为异常处理类
public class ExceptionResultAdvice {
    @ExceptionHandler({SystemException.class})
    public CommonResult doSystemException(SystemException sx){
        return  new CommonResult(Code.SYSTEM_ERR,null,sx.getMessage());
    }
    @ExceptionHandler({BusinessException.class})
    public CommonResult doBusinessException(BusinessException bx){
        return  new CommonResult(Code.SYSTEM_ERR,null,bx.getMessage());
    }
    @ExceptionHandler({Exception.class})
    public CommonResult doException(Exception e){
        return  new CommonResult(Code.SYSTEM_ERR,null,e.getMessage());
    }
}

(三)服务提供者ConsulClientProvider8001

此模块模拟服务的提供者

1.pom.xml

<?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</artifactId>
        <groupId>com.qwy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ConsulClientProvider8001</artifactId>
    <dependencies>
        <!--SpringCloud consul-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--自己的jar-->
        <dependency>
            <groupId>com.qwy</groupId>
            <artifactId>Common-API</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

注意引入对nacos的注册发现依赖:

   <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

2.application.yml

server:
  port: 8001
spring:
  application:
    name: consul-client-provider
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: admin

  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

3.主启动类

 package com.qwy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @Author:齐
 * @Package:com.qwy
 * @Project:springcloud1
 * @name:ConsulClientProvider8001
 * @Date:2022/12/12 16:27
 * @Filename:ConsulClientProvider8001
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulClientProvider8001 {
    public static void main(String[] args) {
        SpringApplication.run(ConsulClientProvider8001.class,args);
    }
}

3.持久层、服务层、控制层

a.持久层

package com.qwy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qwy.bean.Users;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Author:齐
 * @Package:com.qwy.mapper
 * @Project:springcloud1
 * @name:UsersMapper
 * @Date:2022/12/11 21:49
 * @Filename:UsersMapper
 */
@Mapper
public interface UsersMapper extends BaseMapper<Users> {
}

b. 服务层

接口
package com.qwy.service;

import com.qwy.bean.Users;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:齐
 * @Package:com.qwy.service
 * @Project:springcloud1
 * @name:OrderService
 * @Date:2022/12/11 21:47
 * @Filename:OrderService
 */
@Transactional
public interface UsersService {
    boolean save(Users users);
    Users findById(Long id);
}

实现类
package com.qwy.service.impl;

import com.qwy.bean.Users;
import com.qwy.mapper.UsersMapper;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:齐
 * @Package:com.qwy.service.impl
 * @Project:springcloud1
 * @name:UsersServiceImpl
 * @Date:2022/12/11 21:50
 * @Filename:UsersServiceImpl
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public boolean save(Users users) {
        int insert = usersMapper.insert(users);
        return insert>0?true:false;
    }

    @Override
    public Users findById(Long id) {
        return usersMapper.selectById(id);
    }
}

c.业务控制器

 package com.qwy.controller;

import com.qwy.bean.Code;
import com.qwy.bean.CommonResult;
import com.qwy.bean.Users;
import com.qwy.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @Author:齐
 * @Package:com.qwy.controller
 * @Project:springcloud1
 * @name:UsersController
 * @Date:2022/12/11 21:51
 * @Filename:UsersController
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Value("${server.port}")
    private String port;
    @PostMapping
    public CommonResult save(@RequestBody Users users){
        boolean save = usersService.save(users);
        return  new CommonResult(save? Code.SAVE_OK:Code.SAVE_ERR,save);
    }
    @GetMapping("/{id}")
    public CommonResult findById(@PathVariable("id") Long id){
        System.out.println("port:"+port);
        Users users = usersService.findById(id);
        Integer code = users != null ? Code.SELECT_OK : Code.SELECT_ERR;
        String message = users != null ? "" : "查询失败,请稍后查询";
        return new CommonResult(code,users,message);
    }
}

(四)服务提供者ConsulClientProvider8002

此模块参照服务提供者ConsulClientProvider8001

(五)服务消费者ConsulClientConsumer80

1.pom.xml

<?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</artifactId>
        <groupId>com.qwy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>NacosClientConsumer80</artifactId>
    <dependencies>
        <!--nacos-client-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.qwy</groupId>
            <artifactId>Common-API</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.20</version>
        </dependency>
        <!--注意新版必须加入负载均衡-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
    </dependencies>
</project>

注意这里为了支持负载均衡,必须加入负载均衡的依赖:

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
     </dependency>

springcoud已经彻底放弃了ribbon,有了新的负载均衡的支持。

2.application.yml

server:
  port: 80

spring:
  application:
    name: nacos-client-consumer
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/mydb2
    username: root
    password: admin
  cloud:
    nacos:
      server-addr: localhost:8848
#      discovery:
#        username: nacos-client-provider

3.主启动类

package com.qwy;

import com.qwy.config.ApplicationConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;


/**
 * @Author:齐
 * @Package:com.qwy
 * @Project:springcloud1
 * @name:NacosClientConsumer80
 * @Date:2022/12/13 21:54
 * @Filename:NacosClientConsumer80
 */
@SpringBootApplication
@EnableDiscoveryClient
public class NacosClientConsumer80 {
    public static void main(String[] args) {
        SpringApplication.run(NacosClientConsumer80.class,args);
    }
}

4. ApplicationConfig.java

此类为了配置Spring的配置类

package com.qwy.config;


import org.springframework.cloud.client.loadbalancer.LoadBalanced;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

/**
 * @Author:齐
 * @Package:com.qwy.config
 * @Project:springcloud1
 * @name:ApplicationConfig
 * @Date:2022/12/11 4:04
 * @Filename:ApplicationConfig
 */
@Configuration
public class ApplicationConfig {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return  new RestTemplate();
    }
}

5. 持久层、服务层、控制层

a.持久层
 package com.qwy.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qwy.bean.Orders;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Author:齐
 * @Package:com.qwy.mapper
 * @Project:springcloud1
 * @name:OrderMapper
 * @Date:2022/12/11 3:51
 * @Filename:OrderMapper
 */
@Mapper
public interface OrderMapper extends BaseMapper<Orders> {
}

b.服务接口
package com.qwy.service;

import com.qwy.bean.Orders;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author:齐
 * @Package:com.qwy.service
 * @Project:springcloud1
 * @name:OrdersService
 * @Date:2022/12/11 4:00
 * @Filename:OrdersService
 */
@Transactional
public interface OrdersService {
    boolean save(Orders orders);
    Orders findById(Long id);
}

c.服务实现类

package com.qwy.service.impl;

import com.qwy.bean.Orders;
import com.qwy.mapper.OrderMapper;
import com.qwy.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:齐
 * @Package:com.qwy.service.impl
 * @Project:springcloud1
 * @name:OrdersServiceImpl
 * @Date:2022/12/11 4:02
 * @Filename:OrdersServiceImpl
 */
@Service
public class OrdersServiceImpl implements OrdersService {
    
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public boolean save(Orders orders) {
        int insert = orderMapper.insert(orders);
        return insert>0?true:false;
    }


    @Override
    public Orders findById(Long id) {
        Orders orders = orderMapper.selectById(id);
        return orders;
    }
}

d.控制器

package com.qwy.controller;

import com.alibaba.fastjson2.JSONObject;
import com.qwy.bean.*;
import com.qwy.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @Author:齐
 * @Package:com.qwy.controller
 * @Project:springcloud1
 * @name:OrderController
 * @Date:2022/12/11 4:15
 * @Filename:OrderController
 */
@RestController
@RequestMapping("/orders")
public class OrderController {
    private final String CLIENT_PROVIDER_URL="http://nacos-client-provider";
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RestTemplate restTemplate;
    @PostMapping
    public CommonResult save(@RequestBody Orders orders){
        boolean save = ordersService.save(orders);
        return  new CommonResult(save? Code.SAVE_OK:Code.SAVE_ERR,save);
    }
    @GetMapping("/{id}")
    public CommonResult findOrderAndUserById(@PathVariable("id") Long id){
       
        Orders orders = ordersService.findById(id);
        Long usersId = orders.getUsersId();

        CommonResult commonResult = restTemplate.getForObject(CLIENT_PROVIDER_URL+"/users/"+usersId, CommonResult.class, usersId);

        String josn = JSONObject.toJSONString(commonResult.getData());
        Users users = JSONObject.parseObject(josn, Users.class);
        ExtendsOrders extendsOrders= new ExtendsOrders();
        extendsOrders.setUsers(users);
        extendsOrders.setCreateTime(orders.getCreateTime());
        extendsOrders.setId(orders.getId());
        extendsOrders.setName(orders.getName());
        Integer code = orders != null ? Code.SELECT_OK : Code.SELECT_ERR;
        String message = orders != null ? "" : "查询失败";
        return  new CommonResult(code,extendsOrders,message);
    }
}

(六)图示说明

1.启动nacos(因为nacos默认需要集群,这里使用单节点模式)

startup.cmd -m standalone

在这里插入图片描述

2.启动服务提供者和消费者

NacosClientProvider8001,
NacosClientProvider8002,
NacosClientConsumer80

3.浏览器输入

http://localhost:8848/nacos

出现如图所示:
在这里插入图片描述

4.查看对应关系

a.服务提供者与Nacos

在这里插入图片描述

b.服务消费者与Nacos

在这里插入图片描述

c.服务消费者调用在Nacos中注册的服务提供者的名称

在这里插入图片描述
结语:持久不断的学习,才能注入新的血液。写此文章主要为了学习技术的更新的部分。另Nacos的功能不仅仅是服务的注册与发现。因为篇幅问题,这里不再探讨其他的功能,后期补充。最后创作不易,希望对大家有帮助,大家浏览之余留下个小小的赞,本人将不胜感激。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/87269.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

TIA博途_序列化指令Serialize的具体使用方法示例

TIA博途_序列化指令Serialize的具体使用方法示例 序列化指令的基本用途: 首先,我们可以查看TIA博途中的帮助文件说明,如下图所示: 简单总结就是: 把复杂的数据或数据类型(例如UDT、STRUCT等)转换成BYTE或CHAR类型的数组,从而方便数据处理,通常在通信数据的处理中可以…

DBCO-PEG-amine,二苯并环辛炔PEG氨基 MV 1K、2K、3.4K、4K、5K、10K

1、试剂基团反应特点&#xff08;Reagent group reaction characteristics&#xff09;&#xff1a; DBCO用于无铜点击化学。在没有铜催化剂的情况下&#xff0c;与叠氮化合物的反应非常迅速。这种反应是非常迅速&#xff0c;温和&#xff0c;和生物相容性&#xff0c;NH2和带N…

数据结构---KMP算法

一、KMP算法简介 KMP算法是一个字符串匹配算法&#xff0c;对暴力算法BF的一种优化&#xff0c;使得时间复杂度大量的降低。 基本概念&#xff1a; s[]是字符串&#xff0c;简单来说&#xff0c;就是比较长的字符串。p[]是模式串&#xff0c;简单来说&#xff0c;就是比较短的…

使用小爱同学语音控制电脑关机 - Winform C#

使用小爱同学语音控制电脑变关机前言实现原理准备注册巴法云账号接入巴法云接入米家编写程序连接TCP接收信息并运行关机指令发送指令订阅主题添加心跳机制后台运行阻止默认关闭窗口事件完整代码前言 小爱同学应该已经是家喻户晓的了&#xff0c;现在一直用来控制家里的家电。于…

selenium + python自动化测试环境搭建(有手就行)

selenium 是一个web的自动化测试工具&#xff0c;不少学习功能自动化的同学开始首选selenium &#xff0c;相因为它相比QTP有诸多有点&#xff1a; 免费&#xff0c;也不用再为破解QTP而大伤脑筋 小巧&#xff0c;对于不同的语言它只是一个包而已&#xff0c;而QTP需要下载安装…

时序预测 | MATLAB实现PSO-SVM粒子群优化支持向量机时间序列预测

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;修心和技术同步精进&#xff0c;matlab项目合作可私信。 &#x1f34e;个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知。 更多Matlab仿真内容点击&#x1f447; 智能优化算法 …

LeetCode刷题日记之链表II

1.四数相加II 题目描述 解题思路 1.定义一个哈希Map,其中key存放两数之和&#xff0c;value存放两数和出现的次数。 2.遍历统计出nums1和nums元数相加和出现的次数(ab)。 3.遍历nums3和nums4&#xff0c;并求和(cd),统计出(0-(cd))在Map中出现的次数。 4.返回&#xff08;0-(…

央企招聘:中国人民银行2023年度招聘启事

2023年中国外汇交易中心 博士后科研工作站招聘公告 中国外汇交易中心暨全国银行间同业拆借中心&#xff08;以下简称“交易中心”&#xff09;于1994年成立&#xff0c;是中国人民银行直属事业单位&#xff0c;为银行间外汇、货币、债券及其衍生产品提供交易、发行、基准及一线…

如何通过.exe文件控制一台电脑

CVE-2022-21999漏洞 如何实现发送一个.exe文件偷偷控制他人的电脑&#xff1f;这个想法很刑的&#xff0c;所以我只是说明我的实现方式&#xff0c;具体操作建议仅用于hvv等专业领域&#xff0c;请勿以身试法。 首先我们分析一下.exe文件的实际应用场景---windows系统的电脑&am…

11、setoolkit工具 构造钓鱼网站、powershell注入

靶机&#xff1a;192.168.11.105攻击机kail&#xff1a;192.168.11.1061.在kali中启动setoolkitsetoolkit2.利用SET构建钓鱼网站1&#xff09;选择1 Social-Engineering Attacks &#xff08;社会工程学攻击&#xff09;2&#xff09;选择2 Website Attack Vectors &#xff…

Spring Boot 概念、创建和运行 · Spring Boot 的优点 · 启动第一个 Spring Boot · Spring Boot 的注意事项

一、什么是 Spring Boot二、Spring Boot 优点三、Spring Boot 项目创建四、项目目录介绍和运行4.1 运行项目4.2 输出 Hello World五、注意事项5.1 包路径错误5.2 小结&#xff1a;约定大于配置六、总结一、什么是 Spring Boot Spring 的诞生是为了简化 Java 程序的开发的&…

GAMES101-现代计算机图形学入门-闫令琪 课程笔记 - 汇总(上)

一些前言与感慨&#xff1a; 学了再多的AI&#xff0c;终究还是没有办法拒绝计算机图形学的魅力。当初就不该一招不慎&#xff0c;踏入AI的坑。 可惜当年在学校里学计算机图形学的时候&#xff0c;还没有闫令琪这么好的课程&#xff0c;当时学得一知半解&#xff0c;云里雾里…

极市直播回放第106期丨阿里达摩院:兼顾速度与精度的高效目标检测框架DAMO-YOLO

阿里巴巴达摩院智能计算实验室团队设计并开源了一款兼顾速度与精度的目标检测框架DAMO-YOLO&#xff0c;其性能超越了目前的一众YOLO系列方法&#xff0c;在实现精度SOTA的同时&#xff0c;保持了很高的推理速度。DAMO-YOLO是在YOLO框架基础上引入了MAE-NAS、efficient-RepGFPN…

cas:1628790-40-8|脂溶性Cyanine7-COOH|CY7-Carboxylic Acid

cas:1628790-40-8|脂溶性Cyanine7-COOH|CY7-Carboxylic Acid 名称&#xff1a;脂溶性Cyanine7-COOH|CY7-Carboxylic Acid cas:1628790-40-8 英文同义词: Cy7;Colpro;Prothil;R-13615;Cy7-COOH;CY7ACID;Cy7NHS;AY-62022;Cy7,>97%;Sulfo-Cyanine7 中文名称:磺基-CY7羧酸 …

【小甲鱼C语言】课后笔记第一章第四节——数据类型

目录 1、数据类型 2、short 和 long 3. sizeof 运算符 4. signed 和 unsigned 5、课后习题&#xff08;编程题&#xff09; 1、数据类型 在 C 语言里&#xff0c;所谓的数据类型就是坑的大小。我们说变量就是在内存里边挖一个坑&#xff0c;然后给这个坑命名。那么数据类型…

U盘格式化后能恢复数据吗?U盘删除的数据还能恢复吗

U盘格式化后能恢复数据吗&#xff1f;通常情况下&#xff0c;我们U盘里的数据丢失后&#xff0c;它们并没有立即消失&#xff0c;它们只是被系统做了一个标记&#xff0c;将数据存储的位置标记成可写入的状态&#xff0c;只有当新数据写入的时候&#xff0c;这个存储位置才会被…

USB转UART的桥接控制器 国产DPU02能不能软硬件兼容替换CP2102?

DPU02是一个高度集成的USB转UART的桥接控制器&#xff0c;可将RS-232设计更新为USB设计&#xff0c;并简化PCB组件空间。 该DPU02包括了一个USB 2.0全速功能控制器、USB收发器、振荡器、EEPROM和带有完整调制解调控制信号的异步串行数据总线&#xff08;UART&#xff09;控制器…

自动驾驶车辆安全保证机制-Mobileye的RSS模型

自动驾驶汽车(AV)将如何与人类司机安全地共享道路? 成功实现自动驾驶未来的最大威胁之一是对自动驾驶汽车安全驾驶的含义缺乏共识。只有当行业、政府和公众有一个共同的方式来理解和评估自动驾驶汽车(AV)的驾驶技能和安全,他们才会被信任,可以安全地与人类驾驶的车辆一起…

Go1.19.3 数组与切片原理简析

数组 Go语言数组&#xff0c;声明有如下几种方式&#xff1a; var arr1 [10]intarr1[0] 10000var arr2 [10]int{0:0,2:2}var arr3 [...]int{1,2,3}其中arr1只是进行声明&#xff0c;数组在声明时&#xff0c;内存空间已经被开辟过&#xff0c;所以可以赋值。arr2是声明的同…

javafx 编写管理页面 增删改查

注册界面&#xff1a;用户通过输入页面信息&#xff0c;点击注册&#xff0c;将数据存入数据库中。 <Tab text"用户注册"> <content> <AnchorPane minHeight"0.0" minWidth"0.0" prefHeight"761.0" prefWidth"819…