首页 > 其他分享 >第二章 微服务环境搭建

第二章 微服务环境搭建

时间:2023-08-13 10:44:13浏览次数:35  
标签:shop 服务 springframework org import 第二章 com public 搭建

我们本次是使用的电商项目中的商品、订单、用户为案例进行讲解。

2.1 案例准备

 

 

2.1.1 技术选型

maven:3.3.9 数据库:MySQL 5.7 持久层: SpingData Jpa

其他: SpringCloud Alibaba 技术栈

2.1.2 模块设计

springcloud-alibaba 父工程

shop-common 公共模块【实体类】

 

shop-user 用户微服务 【端口: 807x】 shop-product 商品微服务 【端口: 808x】 shop-order 订单微服务 【端口: 809x】

 

 

 

2.1.3 微服务调用

在微服务架构中,最常见的场景就是微服务之间的相互调用。我们以电商系统中常见的用户下单为 例来演示微服务的调用:客户向订单微服务发起一个下单的请求,在进行保存订单之前需要调用商品微 服务查询商品的信息。

我们一般把服务的主动调用方称为服务消费者,把服务的被调用方称为服务提供者

在这种场景下,订单微服务就是一个服务消费者,    商品微服务就是一个服务提供者。

创建工程前准备工作:


create table `shop_order` (
	`oid` bigint (20),
	`number` int (11),
	`pid` int (11),
	`pname` varchar (765),
	`pprice` double ,
	`uid` int (11),
	`username` varchar (765)
); 
create table `shop_product` (
	`pid` int (11),
	`pname` varchar (765),
	`pprice` double ,
	`stock` int (11)
);

create table `shop_user` (
	`uid` int (11),
	`password` varchar (765),
	`telephone` varchar (765),
	`username` varchar (765)
); 

 

2.2 创建父工程

 工程目录如下:

 

创建一个maven 父工程 shop-parent ,然后在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.shop</groupId>
    <artifactId>shop-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>shop-common</module>
        <module>shop-user</module>
        <module>shop-product</module>
        <module>shop-order</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </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-boot.version>2.3.7.RELEASE</spring-boot.version>
        <mysql-connector-java.version>8.0.23</mysql-connector-java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
        <spring-cloud-alibaba.version>2.1.2.RELEASE</spring-cloud-alibaba.version>
    </properties>
    <dependencies>

        <!--springbootjpa的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>javassist</artifactId>
                    <groupId>org.javassist</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.23.1-GA</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <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>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2.3 创建基础模块

  • 创建 shop-common 模块,在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>shop-parent</artifactId>
        <groupId>com.shop</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>shop-common</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

    </dependencies>

</project>

2 创建实体类

查看代码
 //用户
@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;//手机号
}

 

package com.shop.common.entity;
import lombok.Data;
import javax.persistence.*;
//订单
@Data
@Entity
@Table(name = "shop_order")
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;//购买数量
}
package com.shop.common.entity;
import lombok.Data;
import javax.persistence.*;
//商品
@Data
@Entity
@Table(name = "shop_product")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer pid;//主键
    private String pname;//商品名称
    private Double pprice;//商品价格
    private Integer stock;//库存
}

2.4 创建用户微服务

新建一个  shop-user 模块,然后进行下面操作 步骤:

1 创建模块 导入依赖

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

    <artifactId>shop-user</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.shop</groupId>
            <artifactId>shop-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.7.RELEASE</version>
        </dependency>
    </dependencies>
</project>

2. 创建SpringBoot主类

package com.shop;

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

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

3 加入配置文件

application.yml

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

4 创建必要的接口和实现类(controller service dao)

package com.shop.dao;

import com.shop.common.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository<User, Integer> {
}
public interface UserService {
}
package com.shop.controller;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
}

2.5 创建商品微服务

1 创建一个名为 shop_product 的模块,并添加springboot依

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

    <artifactId>shop-product</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.shop</groupId>
            <artifactId>shop-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.7.RELEASE</version>
    </dependency>
        <!--nacos客户端-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
</project>

2 创建工程的主类

package com.shop.product;

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

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

3.创建配置文件yml

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

4. 创建ProductDao接口

package com.shop.product.dao;

import com.shop.common.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductDao extends JpaRepository<Product,Integer> {
}

5. 创建ProductService接口和实现类

package com.shop.product.service;

import com.shop.common.entity.Product;

public interface ProductService {
    public Product findByPid(Integer pid);
}
package com.shop.product.service.impl;

import com.shop.common.entity.Product;
import com.shop.product.dao.ProductDao;
import com.shop.product.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();
    }
}

6.  创建controller

@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;
    }
}

7. 创建configuration 添加jap配置开启扫描 entity,dao ,

package com.shop.product.configuration;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan(basePackages = "com.shop.product.*")
@Configuration
@EnableJpaRepositories(value = "com.shop.product.dao")
@EntityScan(basePackages = "com.shop.common.entity")
public class ProductConfiguration {
}

2.6 创建订单微服务

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

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

    <artifactId>shop-order</artifactId>
    <dependencies>
        <dependency>
            <groupId>com.shop</groupId>
            <artifactId>shop-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.7.RELEASE</version>
        </dependency>
    </dependencies>
</project>

 

2 创建工程的主类

package com.shop.order;

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

3 创建配置文件application.yml

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

4 创建OrderDao接口

package com.shop.order.dao;

import com.shop.common.entity.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderDao extends JpaRepository<Order,Long> {
}

5 创建OrderService接口和实现类

package com.shop.order.service;

import com.shop.common.entity.Order;

public interface OrderService {
    public Order save(Order order);
}
package com.shop.order.service.impl;

import com.shop.common.entity.Order;
import com.shop.order.dao.OrderDao;
import com.shop.order.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 Order save(Order order) {
        return orderDao.save(order);
    }
}

6 载主程序启动类中添加 restTempalet 

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

 7.创建controller



public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @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;
    }
}

8.创建configuration

package com.shop.order.configuration;

import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan(basePackages = "com.shop.order.*")
@Configuration
@EnableJpaRepositories(value = "com.shop.order.dao")
@EntityScan(basePackages = "com.shop.common.entity")
public class ShopConfiguration {
}

9. 通过浏览器访问:localhost:8091/order/prod/1

 

 

 

点击查看代码 ``` ```

标签:shop,服务,springframework,org,import,第二章,com,public,搭建
From: https://www.cnblogs.com/eagle888/p/17626239.html

相关文章

  • 仿微信聊天程序 - 11. 服务端
    本文是仿微信聊天程序专栏的第十一篇文章,主要记录了【米虫IM-服务端】的实现。界面设计仿微信聊天程序的服务端正常来说可能不需要界面,但是为了配置和调试方便,还是开发了一下简单的界面,主要由两部分组成:服务端域名(或IP)端口配置收发数据包日志打印Spring集成仿微信聊天程......
  • SVN服务器部署
    SVN服务器安装与配置[SVN安装](SVN安装|菜鸟教程(runoob.com))SVN创建版本库linux下搭建SVN服务器完全手册官方文档一、安装详见教程:https://www.runoob.com/svn/svn-install.html二、创建版本库新建一个目录用于存储SVN所有文件#mkdir/home/svn新建一个......
  • 第二章 运算符和数学函数
    第二章运算符和数学函数2.1数学运算符:创建序列(两头都会包含)>x<-2:4>x[1]234+加>1+1[1]2-减>2-1[1]1*乘>1*2[1]2/浮点数除法>3/2[1]1.5%/%整数除法>3%/%2[1]1%%余数>3%%2[1]1^或**求幂>2^2[1]4>2**2[1]4......
  • Ubuntu 20.04 使用 vlmscd 搭建 KMS 服务端
    前言为了内网系统激活需要,搭建此客户端。1.下载二进制文件打开项目官网:https://github.com/Wind4/vlmcsd下载项目二进制文件:选择对应系统和架构选择性能较好的含musl库的静态版本将选择的版本重命名为vlmcsd.2.安装到Ubuntu系统中cpvlmcsd/usr/local/bin/ch......
  • CentOS 批量部署用户免密服务器
    一、前言在Linux系统中,SSH(SecureShell)是一种常用的远程登录和文件传输协议。传统的SSH登录需要输入用户密码,既不方便也不安全。为了解决这个问题,我们可以部署SSH的公钥认证,即免密登录。本文将详细介绍如何在CentOS上批量部署用户免密服务器。二、准备环境1台CentOS7.x的服务器(本......
  • CentOS系统上部署PXE服务器步骤
    安装Apache首先,需要安装Apache服务器。可以使用以下命令安装:yuminstallhttpd配置Apache接下来,需要配置Apache服务器,使其能够正确响应PXE请求。在httpd.conf文件中,找到以下行:<Directory"/var/www/html">将该行的AllowOverride选项设置为All,以便能够使用.htaccess文件进行配置。然......
  • Postgres语言服务器介绍
    本文主要介绍Postgres的语言服务器。不是SQL的风格,只是Postgres。状态......
  • Redis主从、哨兵和集群环境搭建
    一、Redis单机安装(1)安装依赖的C语言yuminstall-ygcc-c++automakeautoconflibtoolmaketcl(2)上传安装包并解压cd/usr/local/tmptarzxfredis-5.0.5.tar.gz(3)编译并安装cd/usr/local/tmp/redis-5.0.5/#编译make#安装makeinstallPREFIX=/usr/local/redis(4)开启守护......
  • 多任务版TCP服务端程序开发
    分析当客户端和服务端建立连接成功,创建子线程,使用子线程专门处理客户端的请求,防止主线程阻塞 示例服务端1importsocket2importthreading345#处理客户端函数6defhandle_client(conn_socket,ip_port):7try:8whileTrue:9......
  • 服务器常见问题答疑
    前篇#为什么要写这篇文章呢 现在属于网络时代,服务器的使用越来越广泛,网站搭建、软件开发、游戏开发和区块链等都是需要在服务器里操作搭建的,花时间写这篇文章是希望能有更多的人对服务器有更好的认识 一、##检查哪些尝试入侵服务器的ip命令ubuntu查看尝试登录服务器的ip,一般用......