微服务项目整合与测试

本文详细介绍了一个模拟商城管理系统的微服务项目整合过程,包括Eureka注册中心、Zuul API网关、订单管理和用户管理服务的搭建与配置。同时,介绍了如何使用Swagger-UI作为接口可视化工具,实现API接口的文档生成和测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微服务项目整合

  1. 下载微服务项目
    首先在github上下载一下微服务包后,以mavan项目导入Eclipse。

https://github.com/microservices-demo/microservices-demo

  1. 微服务项目
    此项目模拟的是一个商城管理系统,项目通过一个名为microservice-mallmanagement的maven父项目构建了四个子项目。如下图所示:
    在这里插入图片描述
  2. 项目功能介绍

microservice-eureka-server(eureka注册中心)。
microservice-gateway-zuul(zuul API网关)。
microservice-orderservice(订单管理服务)。
microservice-userservice(用户管理服务)。
部分代码展示

  1. 注册中心配置文件
spring:
    application:
        name: eureka-server # 指定应用名称
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://localhost:${server.port}/eureka/
#      上线测试需要使用以下配置
#     defaultZone: http://eureka-server:${server.port}/eureka/
  1. zuul API网关配置文件
spring:
  application:
    name: gateway-zuul # 指定应用名称

  cloud:
    inetutils:
      preferred-networks:
      - 10.0   # 设置注册到Eureka中心的优选服务地址

server:
  port: 8050

eureka:
  instance:
      prefer-ip-address: true  #优选通过IP地址找到对应的服务名称

  client:
    #配置eureka注册中心地址
    serviceUrl:
       defaultZone: http://localhost:8761/eureka/
#      上线测试需要使用以下配置
#     defaultZone: http://eureka-server:8761/eureka/

#设置Hystrix熔断器判定超时时间
#hystrix:
#  command:
#    default:
#      execution:
#        isolation:
#          thread:
#            timeoutInMilliseconds: 60000
zuul:
  ignoredServices: '*'
  routes:
    user-service:
      path: /user-service/**
      serviceId: user-service
    order-service:
       path: /order-service/**
       serviceId: order-service

  1. 订单管理中心配置文件
#DB Configuration
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.88.121:3306/microservice_mallmanagement
#    与Docker整合时可使用以下配置(也可以使用具体的ip+端口)
#    url: jdbc:mysql://mysql:3306/microservice_mallmanagement
    username: root
    password: root
  application:
      name: order-service # 指定应用名称

  cloud:
    inetutils:
      preferred-networks:
      - 10.0   # 设置注册到Eureka中心的优选服务地址

server:
  port: 7900 # 指定该Eureka实例的端口号
eureka:
  instance:
        prefer-ip-address: true  #优选通过IP地址找到对应的服务名称

  client:
    service-url:
       defaultZone: http://localhost:8761/eureka/  #配置eureka注册中心地址
#      上线测试需要使用以下配置
#     defaultZone: http://eureka-server:8761/eureka/


  1. 订单管理中心控制类代码
package com.itheima.controller;
import com.itheima.mapper.OrderMapper;
import com.itheima.po.Order;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
	@Autowired
	private OrderMapper orderMapper;

	@GetMapping(path="/findOrders/{userid}")
	@HystrixCommand(fallbackMethod = "findOrderfallback") //断路器
	public List<Order> findOrder(@PathVariable("userid") Integer userid) {
		List<Order> orders=  this.orderMapper.selectOrder(userid);
		return  orders;
	}
	//针对上面断路器发现的问题编写回调方法(参数和返回值要一样)
	public List<Order> findOrderfallback(Integer userid) {
		List<Order> orders =new ArrayList<>();
		return orders;
	}
}
  1. 用户管理中心配置文件
#DB Configuration
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  
    url: jdbc:mysql://192.168.88.121:3306/microservice_mallmanagement
#    与Docker整合时可使用以下配置(也可以使用具体的ip+端口)
#    url: jdbc:mysql://mysql:3306/microservice_mallmanagement
    username: root
    password: 123qwe
  application:
      name: user-service # 指定应用名称
  cloud:
      inetutils:
        preferred-networks:
        - 10.0   # 设置注册到Eureka中心的优选服务地址
server:
  port: 8030 # 指定该Eureka实例的端口号
eureka:
  instance:
          prefer-ip-address: true  #优选通过IP地址找到对应的服务名称
  client:
    service-url:
       defaultZone: http://localhost:8761/eureka/  #配置eureka注册中心地址
#      上线测试需要使用以下配置
#     defaultZone: http://eureka-server:8761/eureka/
#客户端动态访问常量配置
ORDERSERVICEURL: http://order-service/
  1. 用户管理中心控制类代码
package com.itheima.controller;

import com.itheima.mapper.UserMapper;
import com.itheima.po.Order;
import com.itheima.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private UserMapper userMapper;
	@Value("${ORDERSERVICEURL}")
	private String ORDERSERVICEURL;

	@GetMapping(path="/findOrders/{username}")
	public List<Order> getOrderByUsername(@PathVariable("username")
												String username) {
		User user = this.userMapper.selectUser(username);
		//使用Ribbon后,可以使用http://order-service/而不用使用ip+端口
		ResponseEntity<List<Order>> rateResponse =
			      restTemplate.exchange(ORDERSERVICEURL
					+"/order/findOrders/"+user.getId(),
					HttpMethod.GET, null, 
					new ParameterizedTypeReference<List<Order>>(){});
		List<Order> orders = rateResponse.getBody();
		return orders;
	}
}

项目启动测试

  1. 首先在Navicat下创建所需要的数据库
CREATE DATABASE microservice_mallmanagement;
USE microservice_mallmanagement;

DROP TABLE IF EXISTS `tb_order`;
CREATE TABLE `tb_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `createtime` datetime DEFAULT NULL,
  `number` varchar(255) DEFAULT NULL,
  `userid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=UTF8;
INSERT INTO `tb_order` VALUES ('1', '2017-10-09 10:15:44', '201709181459001', '1');
INSERT INTO `tb_order` VALUES ('2', '2017-10-24 18:22:12', '201709181459008', '1');

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `address` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=UTF8;
INSERT INTO `tb_user` VALUES ('1', 'beijing', 'shitou');

  1. 数据库展示
    在这里插入图片描述
  2. 启动注册中心,访问网址:http://localhost:8761
    在这里插入图片描述
  3. 测试接口方法:分别通过orderservice和userservice两个服务的地址来访问各自保楼的API接口方法分别为http://localhost:7900/order/findOrders/1和http://localhost:8030/user/findOrders/shitou进行测试
    在这里插入图片描述
    在这里插入图片描述
  4. 测试API网关。分别访问http://localhost:8050/order-service/order/findOrders/1和http://localhost:8050/user-service/user/findOrders/shitou,如下图所示:
    在这里插入图片描述
    在这里插入图片描述

接口可视化工具Swagger-UI

部署接口可视化工具swagger

  1. 下载swagger项目:
    在github上下载swagger项目,网址:

GitHub地址:https://github.com/swagger-api/swagger-ui.git

  1. 添加pom文件中中的Swagger依赖
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>
	</dependencies>
  1. 编写swagger类
package com.itheima.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Date;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
	//定义API接口映射路径	
    public static final String DEFAULT_INCLUDE_PATTERN = "/user/.*";
    private final Logger log = 
    		LoggerFactory.getLogger(SwaggerConfiguration.class);
    @Bean
    public Docket swaggerSpringfoxDocket() {
      log.debug("Starting Swagger");
      StopWatch watch = new StopWatch();
      watch.start();
      //用于生成对应API接口文档的描述信息,可省略
      ApiInfo apiInfo = new ApiInfo("用户管理API接口测试文档","description",
        		"termsOfServiceUrl","contact","version","","");
      Docket docket = new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo)
        .genericModelSubstitutes(ResponseEntity.class)
        .forCodeGeneration(true)
        .genericModelSubstitutes(ResponseEntity.class)
        .directModelSubstitute(java.time.LocalDate.class, String.class)
        .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
        .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
        .select()                
        .paths(regex(DEFAULT_INCLUDE_PATTERN))//匹配路径生成对应接口文档 
        .build();
      watch.stop();
      log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
      return docket;
    }
}

测试接口可视化工具swaager

  1. 在浏览器输入一下地址进入接口可视化工具界面,显示效果如下

http://localhost:7900/swagger-ui.html
在这里插入图片描述

  1. 管理接口测试
    在这里插入图片描述
  2. 用户接口测试
    在这里插入图片描述
    做完此次试验后,我掌握了简单的微服务项目整合方法与swagger-ui就扣可视化工具的使用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值