• SpringCloudAlibaba-入门学习之环境搭建


    环境搭建

    模块设计

    • springcloud-alibaba  父工程
    • shop-common          公共模块【实体类】
    • shop-user                 用户微服务 【端口: 807x】
    • shop-product            商品微服务 【端口: 808x】
    • shop-order                订单微服务 【端口: 809x】

    1:创建一个maven父工程(删掉其他附属文件保留一个pom.xml)如下图目录

    2:引入相关依赖 pom.xml

    <groupId>com.chenpt</groupId>
        <artifactId>springcloud-alibaba</artifactId>
        <packaging>pom</packaging>
        <version>1.0-SNAPSHOT</version>
        <modules>
            <module>shop-user</module>
            <module>shop-product</module>
            <module>shop-common</module>
        </modules>
    
        <!--父工程-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.3.RELEASE</version>
        </parent>
    
    
        <!--依赖版本的锁定-->
        <properties>
            <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
            <!--        <spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>-->
            <spring-cloud-alibaba.version>2.1.0.RELEASE</spring-cloud-alibaba.version>
        </properties>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
                <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>
            </dependencies>
        </dependencyManagement>
    
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.12</version>
            </dependency>
        </dependencies>
    pom.xml配置

    3:创建基础模块

    3.1:shop-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-alibaba</artifactId>
            <groupId>com.chenpt</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>shop-common</artifactId>
    
        <!--依赖-->
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
                <version>2.1.13.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.56</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.6</version>
            </dependency>
        </dependencies>
    
    </project>
    common.pom完整依赖

    创建实体类

    /订单
    @Entity(name = "shop_order")
    @Data
    public class Order {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long oid;//订单id
    
        //用户
        private Integer uid;//用户id
        private String username;//用户名
    
        //商品
        private Integer pid;//商品id
        private String pname;//商品名称
        private Double pprice;//商品单价
    
        //数量
        private Integer number;//购买数量
    }
    order实体
    //商品
    @Entity(name = "shop_product")
    @Data
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer pid;//主键
    
        private String pname;//商品名称
        private Double pprice;//商品价格
        private Integer stock;//库存
    }
    product
    //用户
    @Entity(name = "shop_user")//实体类跟数据表的对应
    @Data
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)//数据库自增
        private Integer uid;//主键
        private String username;//用户名
        private String password;//密码
        private String telephone;//手机号
    }
    user

     3.2:shop-user  

    <dependencies>
            <!--springboot-web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--shop-common-->
            <dependency>
                <groupId>com.chenpt</groupId>
                <artifactId>shop-mommon</artifactId>
                <version>1.0-SNAPSHOT</version>
                <scope>compile</scope>
            </dependency>
    
        </dependencies>
    pom.xml
    server:
      port: 8071
    spring:
      application:
        name: service-user
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/shop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
        username: root
        password: root
      jpa:
        properties:
          hibernate:
            hbm2ddl:
              auto: update
            dialect: org.hibernate.dialect.MySQL5InnoDBDialect
      cloud:
        nacos:
          discovery:
            server-addr: 127.0.0.1:8848
    application.yml

    3.3:shop-product

    <?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-alibaba</artifactId>
            <groupId>com.chenpt</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>shop-product</artifactId>
    
    
        <dependencies>
            <!--springboot-web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--shop-common-->
            <dependency>
                <groupId>com.chenpt</groupId>
                <artifactId>shop-mommon</artifactId>
                <version>1.0-SNAPSHOT</version>
                <scope>compile</scope>
            </dependency>
          
        </dependencies>
    
    
    </project>
    pom.xml
    server:
      port: 8081
    spring:
      application:
        name: service-product
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.61.131:3306/shop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
        username: root
        password: root
      jpa:
        properties:
          hibernate:
            hbm2ddl:
              auto: update
            dialect: org.hibernate.dialect.MySQL5InnoDBDialect
     
    application.yml

    工程主类

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    public class ProductApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ProductApplication.class,args);
        }
    }
    ProductApplication

    创建dao

    import com.chenpt.domain.Product;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface ProductDao extends JpaRepository<Product, Integer> {
    }
    ProductDao

    service接口及实现类

    public interface ProductService {
    
        //根据pid查询商品信息
        Product findByPid(Integer pid);
    
    }
    ProductService
    @Service
    public class ProductServiceImpl implements ProductService {
    
        @Autowired
        private ProductDao productDao;
    
        @Override
        public Product findByPid(Integer pid) {
            return productDao.findById(pid).get();
        }
    
    }
    ProductServiceImpl

    创建cotroller

    @RestController
    @Slf4j
    public class ProductController {
    
        @Autowired
        private ProductService productService;
    
    
        //商品信息查询
        @RequestMapping("/product/{pid}")
        public Product product(@PathVariable("pid") Integer pid) {
            log.info("接下来要进行{}号商品信息的查询", pid);
            Product product = productService.findByPid(pid);
            log.info("商品信息查询成功,内容为{}", JSON.toJSONString(product));
            return product;
        }
    
    }
    ProductController

     启动工程,等到数据库表创建完毕之后,加入测试数据

    INSERT INTO shop_product VALUE(NULL,'小米','1000','5000');
    INSERT INTO shop_product VALUE(NULL,'华为','2000','5000');
    INSERT INTO shop_product VALUE(NULL,'苹果','3000','5000');
    INSERT INTO shop_product VALUE(NULL,'OPPO','4000','5000');

    3.4:shop-order

    <?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-alibaba</artifactId>
            <groupId>com.chenpt</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>shop-order</artifactId>
    
        <dependencies>
            <!--springboot-web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--shop-common-->
            <dependency>
                <groupId>com.chenpt</groupId>
                <artifactId>shop-mommon</artifactId>
                <version>1.0-SNAPSHOT</version>
                <scope>compile</scope>
            </dependency>
            
        </dependencies>
    
    
    </project>
    pom.xml
    @SpringBootApplication
    public class OrderApplication {
        public static void main(String[] args){
            SpringApplication.run(OrderApplication.class);
        }
    
        @Bean
        public RestTemplate getRestTemplate() {
           return new RestTemplate();
        }
    
    }
    orderApplication

    dao

    public interface OrderDao extends JpaRepository<Order,Integer> {
    }

    service

    public interface OrderService {
        void save(Order order);
    }

    serviceImpl

    @Service
    public class OrderServiceImpl implements OrderService {
    
        @Autowired
        private OrderDao orderDao;
    
    
        @Override
        public void save(Order order) {
            orderDao.save(order);
        }
    }
    @Slf4j
    @RestController
    @RequestMapping("/order")
    public class OrderController {
    
        private static final String PRODUCT_URL = "http://localhost:8081/product/";
        private static final String PRODUCT_SERVER = "service-product";
    
        @Autowired
        private OrderService orderService;
        @Autowired
        private RestTemplate restTemplate;
    
       /**
         * 采用restTemplate调用商品微服务
         * 硬编码风格 后期不容易维护   无法实现集群
         * @param pid
         * @return
         */
        @GetMapping("/prod/{pid}")
        public Order order3(@PathVariable("pid") Integer pid){
            log.info(">>>客户下单,调用商品微服务查询商品信息<<<");
            // 采用restTemplate调用
            Product product = restTemplate.getForObject(PRODUCT_URL+pid, Product.class);
            log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
            Order order = new Order();
            order.setUid(1);
            order.setUsername("测试用户1");
            order.setPid(product.getPid());
            order.setPname(product.getPname());
            order.setPprice(product.getPprice());
            order.setNumber(1);
            orderService.save(order);
            return order;
        }
    }
    OrderController

    至此整个环境就算搭建完毕,不过目前没接入微服务的组件,也就属于maven多模块开发 进行了拆分

    通过orderController模拟下单请求  可以发现order服务调用商品服务采用的是restTemplate方式,其中商品服务的信息都是硬编码到order服务中,其中弊端一目了然

    比如:

    1.   商品服务挂了,将导致整个服务不可用
    2.   地址变更,手动修改
    3.   服务增多后期维护复杂
    4.   多个服务提供者无法实现负载均衡

    接下来就以此项目为基础进行微服务学习  

  • 相关阅读:
    Android使用LocalSocket抓取数据
    求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
    链表A和B的有序合并,合并过程不产生新的节点,合并后B消失
    Android中intent如何传递自定义数据类型
    字符串的排列组合问题
    android.net.LocalSocket
    [转]OWC生成柱图,线图,饼图
    利用C#对远程服务进行操作
    域备份&域还原
    ActiveReports for .NET 简单使用
  • 原文地址:https://www.cnblogs.com/chenpt/p/13427723.html
Copyright © 2020-2023  润新知