微服务环境搭建(spring cloud Alibaba)(一)

模块: 商品模块, 订单模块, 用户模块

一. 1. 技术选型以及准备工作

maven : 3.8.8版本

数据库: MySQL 8.0.32

持久层: springData , jpa

其他java环境 : SpringCloud Alibaba 技术栈

2.  模块 设计 

springcloud- alibaba 父工程

shop - common 公共模块 [ 实体类 ]

shop - user 用户服务 [ 端口号:  807x ]

shop - product 商品微服务 [ 端口: 808x ]

shop - order 订单微服务 [ 端口: 809 x] 

简单架构如下图: 

微服务环境搭建(spring cloud Alibaba)(一)_第1张图片

 3.  微服务 实现简单介绍

         在微服务架构中,最常见的场景就是微服务之间的相互调用.在电商系统重常见的用户下单 来掩饰微服务之间的调用, 客户想订单微服务发起一个下单的请求 , 在尽心保存订单之前需要调用商品微服务查询商品信息

主动调用: 服务消费者                  被动调用:  服务提供者

微服务环境搭建(spring cloud Alibaba)(一)_第2张图片

 二 . 1. 创建父工程项目(记得查看版本)

微服务环境搭建(spring cloud Alibaba)(一)_第3张图片

 微服务环境搭建(spring cloud Alibaba)(一)_第4张图片

 微服务环境搭建(spring cloud Alibaba)(一)_第5张图片

微服务环境搭建(spring cloud Alibaba)(一)_第6张图片

相对应的maven依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
    
    com.itheima
    springcloud-alibaba
    1.0-SNAPSHOT
    pom
    
        1.8
        UTF-8
        UTF-8
        Greenwich.RELEASE
        2.1.0.RELEASE
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
            



                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                ${spring-cloud-alibaba.version}
                pom
                import
            
        
    



三 . 1. 创建公共基础模块 shop- common

微服务环境搭建(spring cloud Alibaba)(一)_第7张图片

 微服务环境搭建(spring cloud Alibaba)(一)_第8张图片

 微服务环境搭建(spring cloud Alibaba)(一)_第9张图片

 导入相对应的pom.xml ,



    
        springcloud-alibaba
        com.itheima
        1.0-SNAPSHOT
    
    4.0.0

    shop-common

    
        8
        8
    

    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        


        
            org.projectlombok
            lombok
        

        
            com.alibaba
            fastjson
            1.2.76
        

        
            mysql
            mysql-connector-java
            8.0.32
        
    

如图所示: 

微服务环境搭建(spring cloud Alibaba)(一)_第10张图片

 在shop-common中新建com. example. server. pojo包

创建实体类user 

package com.example.server.pojo;


import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@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;//手机号
}

创建实体类Product

package com.example.server.pojo;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

//商品
@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;//库存
}

创建实体类 Order

package com.example.server.pojo;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

//订单
@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;//购买数量
}

四. 搭建用户微服务模块shop-user

步骤: 1 创建模块 导入依赖

微服务环境搭建(spring cloud Alibaba)(一)_第11张图片

目录结构: 

微服务环境搭建(spring cloud Alibaba)(一)_第12张图片

2 创建SpringBoot主类

package com.example;

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

@SpringBootApplication
public class ShopUserApplication {

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

}

3 加入配置文件

4 创建必要的接口和实现类(controller service dao) 新建一个 shop-user 模块,然后进行下面操作 1 创建pom.xml



    
        springcloud-alibaba
        com.itheima
        1.0-SNAPSHOT
    
    4.0.0
    shop-user
    
        
            com.itheima
            shop-common
            1.0-SNAPSHOT
        
    

 5. 创建配置文件 application.yml

server:
  port: 8071
spring:
  application:
    name: service-product
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///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

五. 搭建商品微服务模块 shop-product

微服务环境搭建(spring cloud Alibaba)(一)_第13张图片

pom.xml文件



    
        springcloud-alibaba
        com.itheima
        1.0-SNAPSHOT
    
    4.0.0
    shop-product
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.itheima
            shop-common
            1.0-SNAPSHOT
        
    

编写主类 springboot执行类

package com.example;

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

@SpringBootApplication
public class ShopProductApplication {

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

}

创建配置文件application.yml

server:
  port: 8081
spring:
  application:
    name: service-product
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///springcloud_shop?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 123456
  jpa:
    properties:
      hibernate:
        hbm2ddl:
          auto: update
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

创建在com.example.  productDao接口

package com.example.dao;

import com.example.server.pojo.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductDao extends JpaRepository {
}

创建ProductService接口和实现类

ProductService

package com.example.service;

import com.example.server.pojo.Product;

public interface ProductService {
    Product findByPid(Integer pid);
}

ProductServiceimpl

package com.example.service.impl;

import com.example.dao.ProductDao;
import com.example.server.pojo.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;



    @Override
    public Product findByPid(Integer pid) {
        return productDao.findById(pid).get();
    }
}

创建Controller

package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.server.pojo.Product;
import com.example.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class ProductController {
    @Autowired
    private ProductService productService;


    @GetMapping("/product/{pid}")
    public Product product(@PathVariable("pid") Integer pid) {
        Product product = productService.findByPid(pid);
        log.info("查询到商品:" + JSON.toJSONString(product));
        return product;
    }

}

创建MySQL数据库: 

create database  springcloud_shop;
use springcloud_shop;


create table  shop_product (
pid int ,
pname VARCHAR(10) not NULL,

pprice  VARCHAR(10) not null,
stock VARCHAR(10) not null

);

create table shop_user(
uid int not null primary key,
username VARCHAR(20) ,

password VARCHAR(20),

telephone VARCHAR(11)

);
delete from shop_user

create table shop_user (
uid integer not null auto_increment, 
userpassword varchar(255), 
telephone varchar(255), 
username varchar(255), 
primary key (uid)

) engine=InnoDB

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


通过浏览器访问服务 localhost:8081/product/1

微服务环境搭建(spring cloud Alibaba)(一)_第14张图片

六. 微服务搭建 订单模块 shop-order

创建一个名为 shop-order 的模块,并添加springboot依赖



    
        springcloud-alibaba
        com.itheima
        1.0-SNAPSHOT
    
    4.0.0
    shop-order
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.itheima
            shop-common
            1.0-SNAPSHOT
        
    

创建springboot执行类

package com.example;

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

@SpringBootApplication
public class ShopOrderApplication {

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

}

在com.example.serve..dao 

OrderDao接口

package com.example.server.dao;

import com.example.server.pojo.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderDao extends JpaRepository {
}

com.example.serve包 接口

OrderService

package com.example.server.service;

import com.example.server.pojo.Order;

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

OrderServiceImpl

package com.example.server.service.impl;

import com.example.server.dao.OrderDao;
import com.example.server.pojo.Order;
import com.example.server.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Override
    public void save(Order order) {
        orderDao.save(order);
    }
}

创建RestTemplate 通过restTemplate调用商品微服务

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

创建controller

package com.example.server.controller;

import com.alibaba.fastjson.JSON;
import com.example.server.pojo.Order;
import com.example.server.pojo.Product;
import com.example.server.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@Slf4j
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService;
    //准备买1件商品
    @GetMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info(">>客户下单,这时候要调用商品微服务查询商品信息");
//通过restTemplate调用商品微服务
        Product product = restTemplate.getForObject(
                "http://localhost:8081/product/" + pid, Product.class);
        log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(product.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        orderService.save(order);
        return order;
    }
}

启动服务之后访问:  localhost:8091/order/prod/1

这样简单的微服务环境搭建好了

微服务环境搭建(spring cloud Alibaba)(一)_第15张图片

你可能感兴趣的:(微服务,微服务,java,spring)