一、使用maven从零开始搭建SpringCloud项目

SpringCloud学习笔记


2020/7/11


微服务架构

一、使用maven从零开始搭建SpringCloud项目_第1张图片 一、使用maven从零开始搭建SpringCloud项目_第2张图片

技术路线

一、使用maven从零开始搭建SpringCloud项目_第3张图片

(红色代表已淘汰技术)

搭建项目环境

(思路:先创建父工程,修改pom文件,再添加一个个的moudle)

  • 使用Maven创建一个父工程(site模板)

    一、使用maven从零开始搭建SpringCloud项目_第4张图片

  • 设置编码

    一、使用maven从零开始搭建SpringCloud项目_第5张图片

  • 注解生效激活

    一、使用maven从零开始搭建SpringCloud项目_第6张图片

  • 设置java编译版本

    一、使用maven从零开始搭建SpringCloud项目_第7张图片

  • 删除src文件

一、使用maven从零开始搭建SpringCloud项目_第8张图片

  • 修改pom文件

    • 设置标签

      <packaging>pompackaging>
      
    • 统一管理jar包版本

      <properties>
          <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
          <maven.compiler.source>1.8maven.compiler.source>
          <maven.compiler.target>1.8maven.compiler.target>
          <junit.version>4.12junit.version>
          <lombok.version>1.16.18lombok.version>
          <log4j.version>1.2.17log4j.version>
          <mysql.version>8.0.18mysql.version>
          <druid.version>1.1.16druid.version>
          <mybatis.spring.boot.version>2.1.1mybatis.spring.boot.version>
      properties>
      
      

      maven.compiler.source:设置编译的jdk版本

    • 子模块继承之后,提供作用:锁定版本+子module不用写groupId和version

       <dependencyManagement>
          <dependencies>
            <dependency>
              <groupId>org.apache.maven.pluginsgroupId>
              <artifactId>maven-project-info-reports-pluginartifactId>
              <version>3.0.0version>
            dependency>
            
            <dependency>
              <groupId>org.springframework.bootgroupId>
              <artifactId>spring-boot-dependenciesartifactId>
              <version>2.2.2.RELEASEversion>
              <type>pomtype>
              <scope>importscope>
            dependency>
            
            <dependency>
              <groupId>org.springframework.cloudgroupId>
              <artifactId>spring-cloud-dependenciesartifactId>
              <version>Hoxton.SR1version>
              <type>pomtype>
              <scope>importscope>
            dependency>
            <dependency>
              <groupId>org.mybatis.spring.bootgroupId>
              <artifactId>mybatis-spring-boot-starterartifactId>
              <version>${mybatis.spring.boot.version}version>
            dependency>
            
            <dependency>
              <groupId>junitgroupId>
              <artifactId>junitartifactId>
              <version>${junit.version}version>
            dependency>
            
            <dependency>
              <groupId>log4jgroupId>
              <artifactId>log4jartifactId>
              <version>${log4j.version}version>
            dependency>
            <dependency>
              <groupId>com.alibaba.cloudgroupId>
              <artifactId>spring-cloud-alibaba-dependenciesartifactId>
              <version>2.1.0.RELEASEversion>
              <type>pomtype>
              <scope>importscope>
            dependency>
            
            <dependency>
              <groupId>mysqlgroupId>
              <artifactId>mysql-connector-javaartifactId>
              <version>${mysql.version}version>
              <scope>runtimescope>
            dependency>
            
            <dependency>
              <groupId>com.alibabagroupId>
              <artifactId>druidartifactId>
              <version>${druid.version}version>
            dependency>
          dependencies>
        dependencyManagement>
      

创建SpringBoot服务提供者子模块

思路:建Module、改Pom、写Yml、主启动、业务类

创建Moudle

一、使用maven从零开始搭建SpringCloud项目_第9张图片

一、使用maven从零开始搭建SpringCloud项目_第10张图片

修改Pom文件

继承了父工程之后,子模块只需写GAV中的A

一、使用maven从零开始搭建SpringCloud项目_第11张图片

  • 添加依赖

     <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-actuatorartifactId>
            dependency>
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
            dependency>
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druid-spring-boot-starterartifactId>
                <version>1.1.10version>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-jdbcartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-devtoolsartifactId>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
        dependencies>
    
编写application.yml文件

一、使用maven从零开始搭建SpringCloud项目_第12张图片

内容如下

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 23456789
    url: jdbc:mysql://localhost:3306/springcloud?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8


mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.sise.entities

注:

image-20200712111111105

  • mapper-location:扫描resources/mapper中的xml文件
  • type-aliases-package:所有entities别名类所在的包
创建启动类

一、使用maven从零开始搭建SpringCloud项目_第13张图片

代码如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class paymentMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(paymentMain8001.class,args);
    }

}
编写业务类
  • entities包

    CommenResult类:

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class CommentResult<T> {
        private Integer code;
        private String message;
        private T data;
    
        public CommentResult(Integer code,String message){
            this(code,message,null);
        }
    }
    

    Payment类:

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Payment implements Serializable {
        private Long id;
        private String serial;
    }
    
  • dao包

    PaymentDao接口:

    @Mapper
    public interface PaymentDao {
        public int create(Payment payment);
        public Payment getPaymentById(@Param("id") long id);
    }
    
    

    PaymentDao类:

    import com.sise.entities.Payment;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    
    @Mapper
    public interface PaymentDao {
        public int create(Payment payment);
        public Payment getPaymentById(@Param("id") long id);
    }
    
  • resources/mapper/PaymentMapper.xml:

    
    
    <mapper namespace="com.sise.dao.PaymentDao">
        <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
            insert into payment(serial) values (#{serial})
        insert>
    
    
        <resultMap id="BaseResultMap" type="Payment">
            <id column="id" property="id" jdbcType="BIGINT"/>
            <id column="serial" property="serial" javaType="VARCHAR"/>
        resultMap>
        <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
            select * from payment where id=#{id}
        select>
    mapper>
    
    
  • service包

    PaymentService接口:

    import com.sise.entities.Payment;
    import org.apache.ibatis.annotations.Param;
    
    public interface PaymentService {
        public int create(Payment payment);
        public Payment getPaymentById(@Param("id") Long id);
    }
    
    

    PaymentServiceImp类:

    import com.sise.dao.PaymentDao;
    import com.sise.entities.Payment;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    
    @Service
    public class PaymentServiceImp implements PaymentService{
        
        @Resource
        private PaymentDao paymentDao;
        
        @Override
        public int create(Payment payment) {
            return paymentDao.create(payment);
        }
    
        @Override
        public Payment getPaymentById(Long id) {
            return paymentDao.getPaymentById(id);
        }
    }
    
    
  • controller包

    PaymentController类:

    import com.sise.entities.CommentResult;
    import com.sise.entities.Payment;
    import com.sise.service.PaymentService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    @Slf4j
    public class PaymentController {
    
        @Resource
        private PaymentService paymentService;
    
        @PostMapping(value = "/payment/create")
        public CommentResult create(Payment payment) {
            int result = paymentService.create(payment);
            log.info("*****插入结果:"+result);
    
            if (result>0){
                return new CommentResult(200,"插入数据成功",result);
            }else {
                return new CommentResult(444,"插入数据失败");
            }
        }
    
        @GetMapping(value = "/payment/get/{id}")
        public CommentResult getPaymentById(@PathVariable("id") Long id){
            Payment payment=paymentService.getPaymentById(id);
            log.info("*****查找结果:"+payment);
    
            if(payment!=null){
                return new CommentResult(200,"查询成功",payment);
            }else {
                return new CommentResult(444,"没有记录");
            }
        }
    }
    
测试
  • get请求

    image-20200712165950000

  • post请求

    一、使用maven从零开始搭建SpringCloud项目_第14张图片

创建SpringBoot服务消费者子模块

创建Moudle

一、使用maven从零开始搭建SpringCloud项目_第15张图片

修改Pom文件

<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>my-springcloudartifactId>
        <groupId>com.sisegroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>cloud-consumer-order80artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
project>
编写application.yml文件

设置端口为80

一、使用maven从零开始搭建SpringCloud项目_第16张图片

创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}
编写业务类
  • entities包

    Payment类:

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import java.io.Serializable;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Payment implements Serializable {
        private Long id;
        private String serial;
    }
    

    CommentResult类:

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class CommentResult<T> {
        private Integer code;
        private String message;
        private T data;
    
        public CommentResult(Integer code,String message){
            this(code,message,null);
        }
    }
    
    
  • config包

    config配置类:

    将RestTemplate注入到springboot容器中

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    @Configuration
    public class ApplicationContextConfig {
    
        @Bean
        public RestTemplate getRestTemplate(){
            return new RestTemplate();
        }
        
        //注解@bean:相当于在applicationContext.xml中的
    }
    
  • controller包

    import com.sise.entities.CommentResult;
    import com.sise.entities.Payment;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import javax.annotation.Resource;
    
    @RestController
    @Slf4j
    public class OderController {
    
        public static final String PAYMENT_URL="http://localhost:8001";
    
        @Resource
        RestTemplate restTemplate;
    
        @GetMapping("/consumer/payment/create")
        public CommentResult<Payment> create(Payment payment){
            return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommentResult.class);
        }
    
        @GetMapping("/consumer/payment/get/{id}")
        public CommentResult<Payment> getPayment(@PathVariable("id") Long id){
            return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommentResult.class);
        }
    }
    
    

    注:需要在PaymentController中添加@RequestBody

    一、使用maven从零开始搭建SpringCloud项目_第17张图片

测试

nal String PAYMENT_URL=“http://localhost:8001”;

  @Resource
  RestTemplate restTemplate;

  @GetMapping("/consumer/payment/create")
  public CommentResult create(Payment payment){
      return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommentResult.class);
  }

  @GetMapping("/consumer/payment/get/{id}")
  public CommentResult getPayment(@PathVariable("id") Long id){
      return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommentResult.class);
  }

}




注:需要在PaymentController中添加@RequestBody

[外链图片转存中...(img-80NGFltt-1604759997286)]





#### 测试

![image-20200712222547017](https://img-blog.csdnimg.cn/img_convert/04ff2f8e87121c9a2c6f0058c1bb1211.png)

你可能感兴趣的:(SpringCloud,java,spring,spring,boot,后端)