springcloud教程(二):搭建服务提供者和调用者

搭建的springcloud工程码云地址:https://gitee.com/fanhua_shijie/springcloud
笔记原文码云地址:https://gitee.com/fanhua_shijie/ibolg
笔记在线访问地址:https://fanhua_shijie.gitee.io/ibolg

一、搭建环境步骤

  1. 新建module
  2. pom.xml引入依赖
  3. 配置文件application.yml
  4. springboot启动类
  5. 业务类

二、新建父类工程

  1. 新建父类工程project

    • 删除src文件夹。

    • 修改编码

      • setting -> Editor -> file encoding
    • 注解生效

      • setting -> Build -> Compiler -> Annotation Processors
    • jdk编译版本选择

      • setting -> Build -> Compiler -> java Compiler
  2. 修改pom.xml

    <!-- 统一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.21</druid.version>
        <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version>
    </properties>
    
    <!-- dependencyManagement 只声明不引入,子类需要自己引入依赖,如果没有指定版本,则继承父类 -->
    <dependencyManagement>
        <dependencies>
            <!--spring boot 2.2.2-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.2.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud Hoxton.SR1-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring cloud alibaba 2.1.0.RELEASE-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <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>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>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <!-- springboot 打包依赖 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
    

三、新建公共module

  1. 新建module

    common-api

  2. pom.xml引入依赖

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <!--
                当optional为true则说明该依赖禁止依赖传递
                <optional>true</optional>
                -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.1</version>
        </dependency>
    </dependencies>
    
  3. 创建公共类

    com.hui.cloud.entity.Department.java

    com.hui.cloud.entity.ResponseResult.java

  4. maven打包

    idea侧边栏maven -> install

四、新建服务提供者module

  1. 新建module

    provider-department8001

  2. pom.xml引入依赖

    <dependencies>
        <!--  引入自定义jar  -->
        <dependency>
            <groupId>com.hui.cloud</groupId>
            <artifactId>common-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.2.2.RELEASE</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.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    
  3. application.yml配置文件

    # 服务端口号
    server:
      port: 8001
      
    spring:
      application:
        # 服务名
        name: provider-department
      datasource:
        # 数据源类型
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8&useSSL=false
        username: root
        password: root
    mybatis:
      # 指定实体类的包名
      type-aliases-package: com.hui.cloud.entity
      # mapper文件位置
      mapper-locations: classpath:mapper/*.xml
    
  4. 编写springboot入口程序

    @SpringBootApplication
    public class ProviderDepartment8001Main {
    
        public static void main(String[] args) {
            SpringApplication.run(ProviderDepartment8001Main.class, args);
        }
    }
    
  5. 业务类

    • controller

       package com.hui.cloud.controller;
       
       import com.hui.cloud.entity.Department;
       import com.hui.cloud.entity.ResponseResult;
       import com.hui.cloud.service.DepartmentService;
       import lombok.extern.slf4j.Slf4j;
       import org.springframework.web.bind.annotation.*;
       import javax.annotation.Resource;
       
       @RestController
       @RequestMapping("/department")
       @Slf4j
       public class DepartmentController {
           @Resource
           private DepartmentService departmentService;
       
           @GetMapping("/get/{id}")
           public ResponseResult getDepartById(@PathVariable("id") long id){
               log.info("接收到的参数为:"+id);
               Department department = departmentService.getDepartmentById(id);
               if(department != null){
                   return new ResponseResult(200, "查询成功!查询id:" + id, department);
               }else{
                   return new ResponseResult(400,"查询结果为空,查询id:"+id,null);
               }
           }
           @PostMapping("/save")
           public ResponseResult save(Department department){
               log.info("请求参数:"+department);
               long result = departmentService.save(department);
               if(result > 0){
                   return new ResponseResult(200,"新增部门成功!",result);
               }else{
                   return new ResponseResult(400,"新增部门失败!",result);
               }
           }
       }
       
      
    • service

       package com.hui.cloud.service.impl;
       
       import com.hui.cloud.dao.DepartmentMapper;
       import com.hui.cloud.entity.Department;
       import com.hui.cloud.service.DepartmentService;
       import org.springframework.stereotype.Service;
       
       import javax.annotation.Resource;
       import java.sql.Timestamp;
       import java.util.Date;
       
       @Service
       public class DepartmentServiceImpl implements DepartmentService {
       
           @Resource
           private DepartmentMapper departmentMapper;
       
           @Override
           public Department getDepartmentById(long id) {
               return departmentMapper.getDepartmentById(id);
           }
       
           @Override
           public long save(Department department) {
               department.setCreatedate(new Timestamp(new Date().getTime()));
               departmentMapper.save(department);
               // insert返回主键,需要使用对象来获取
               return department.getId();
           }
       }
       
      
       package com.hui.cloud.service;
       import com.hui.cloud.entity.Department;
       
       public interface DepartmentService {
       
           /**
            * 根据id查询部门信息
            * @param id
            * @return
            */
           public Department getDepartmentById(long id);
       
           /**
            * 新增部门信息
            * @param department
            * @return
            */
           public long save(Department department);
       }
       
      
    • dao

       package com.hui.cloud.dao;
       
       import com.hui.cloud.entity.Department;
       import org.apache.ibatis.annotations.Mapper;
       
       /**
        * 最好使用@Mapper 注解,而不是@Repository
        * 这样的话,就不需要在启动类上增加@MapperScan 注解
        */
       @Mapper
       public interface DepartmentMapper {
           public Department getDepartmentById(long id);
           public long save(Department department);
       }
      
    • mapper

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.hui.cloud.dao.DepartmentMapper">
          
          <select id="getDepartmentById" parameterType="java.lang.Long" resultMap="Department">
              select * from department where id = #{id}
          </select>
      	<!-- 返回的主键,需要通过传入的对象来接受 -->
          <insert id="save" parameterType="Department" useGeneratedKeys="true" keyProperty="id">
              insert into department(departmentname, superiordepartmentid, createdate)
                            values (#{departmentname},#{superiordepartmentid},#{createdate})
          </insert>
      </mapper>
      

      业务类的包,要放在springboot入口程序的子包,保证springboot可以扫描到。

  6. 热部署

    1. 引入热部署依赖

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-devtools</artifactId>
          <version>2.2.2.RELEASE</version>
      </dependency>
      
    2. idea配置

    在这里插入图片描述
    3. ctrl+shift+alt+/ --> Registry
    在这里插入图片描述

  7. department建表语句

    create table department(
      id bigint(20) not null auto_increment,
      departmentname varchar(30),
      superiordepartmentid bigint(20),
      createdate timestamp,
      primary key(id)
    )engine = InnoDB
      AUTO_INCREMENT=1
      DEFAULT CHARSET =utf8;
    

五、新建服务消费者module

  1. 新建module

    consumer-department80

  2. pom.xml

    <dependencies>
        <!-- 不需要的包,就不要引入,springboot的自动装载机制,如果引入不需要的jar会导致报错 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <!--  引入自定义jar  -->
        <dependency>
            <groupId>com.hui.cloud</groupId>
            <artifactId>common-api</artifactId>
            <version>${project.version}</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>
    </dependencies>
    
  3. application.yml

    server:
      port: 80
    spring:
      application:
        name: consumer-department
    
    # 服务提供者地址
    provider:
      department:
        url: http://localhost:8001
    
    
  4. springboot启动类

    @SpringBootApplication
    public class ConsumerDepartment80Main {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerDepartment80Main.class, args);
        }
    }
    
  5. 编写controller调用服务提供者

    @RestController
    @RequestMapping("/consumer/department")
    @Slf4j
    public class ConsunmerDepartmentController {
    
        @Value("${provider.department.url}")
        private String providerDepartmentUrl;
    
        //注入spring 提供的restful 风格接口
        @Resource
        private RestTemplate restTemplate;
    
        /**
         * 通过id 获取部门信息
         * @param id
         * @return
         */
        @GetMapping("/get/{id}")
        public ResponseResult getDepartmentByID(@PathVariable("id") long id){
            ResponseResult result = restTemplate.getForObject(providerDepartmentUrl + "/department/get/" + id, ResponseResult.class);
            return result;
        }
    
        /**
         * 新增部门信息,并返回新增部门的id
         * @param department
         * @return
         */
        @PostMapping("/save")
        public ResponseResult save(Department department){
            return restTemplate.postForObject(providerDepartmentUrl + "/department/save", department, ResponseResult.class);
        }
    }
    
    

六、Postman测试

  1. 测试save

    在这里插入图片描述

  2. 测试get

    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值