小言_互联网的博客

秒杀项目之mybatis与微服务注册

663人阅读  评论(0)

目录

一、微服务项目集成MybatisPlus

创建自动生成代码子模块

创建商品服务子模块

二、微服务项目集成Freemarker

三、SpringBoot整合微服务&gateway&nginx

gateway

整合微服务之商品服务zmall-product

创建并配置网关gateway服务

安装配置Windows版nginx

安装配置SwitchHosts

请求链路测试


一、微服务项目集成MybatisPlus

创建自动生成代码子模块

1.基于maven方式创建子模块zmall-generator,用于结合mybatis-plus生成代码。

2. 在zmall-generator中引入mybatis-plus-generator依赖。该模块专用于mybatis-plus的代码生成,所以单独在此引入该依赖即可。

<!-- mybatis-plus-generator依赖 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.4.0</version>
</dependency>

3. 在src/main/resources下创建templates目录,并导入mybatis-generator生成代码模板页

4.在src/main/java下创建包com.zking.zmall,并导入generator下的CodeGenerator类用于代码生成

 CodeGenerator 


  
  1. package com.zking.zmall.generator;
  2. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
  3. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  4. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  5. import com.baomidou.mybatisplus.generator.AutoGenerator;
  6. import com.baomidou.mybatisplus.generator.InjectionConfig;
  7. import com.baomidou.mybatisplus.generator.config.*;
  8. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  9. import com.baomidou.mybatisplus.generator.config.rules.DateType;
  10. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  11. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Scanner;
  15. public class CodeGenerator {
  16. //数据库连接参数
  17. public static String driver = "com.mysql.jdbc.Driver";
  18. public static String url = "jdbc:mysql://localhost:3306/zmall?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
  19. public static String username= "root";
  20. public static String password= "123456";
  21. //父级别包名称
  22. public static String parentPackage = "com.zking.zmall";
  23. //项目名设置(如果是SpringCloud项目则需要设置,其他为""即可)
  24. public static String projectName= "/zmall-generator";
  25. //代码生成的目标路径
  26. public static String generateTo = "/src/main/java";
  27. //mapper.xml的生成路径
  28. public static String mapperXmlPath = "/src/main/resources/mapper";
  29. //控制器的公共基类,用于抽象控制器的公共方法,null值表示没有父类
  30. public static String baseControllerClassName ;
  31. //业务层的公共基类,用于抽象公共方法
  32. public static String baseServiceClassName ;
  33. //作者名
  34. public static String author = "zking";
  35. //模块名称,用于组成包名
  36. public static String modelName = "model";
  37. /**
  38. * <p>
  39. * 读取控制台内容
  40. * </p>
  41. */
  42. public static String scanner (String tip) {
  43. Scanner scanner = new Scanner(System.in);
  44. StringBuilder help = new StringBuilder();
  45. help.append( "请输入" + tip + ":");
  46. System.out.println(help.toString());
  47. if (scanner.hasNext()) {
  48. String ipt = scanner.next();
  49. if (StringUtils.isNotBlank(ipt)) {
  50. return ipt;
  51. }
  52. }
  53. throw new MybatisPlusException( "请输入正确的" + tip + "!");
  54. }
  55. public static void main (String[] args) {
  56. // 代码生成器
  57. AutoGenerator mpg = new AutoGenerator();
  58. // 全局配置
  59. GlobalConfig gc = new GlobalConfig();
  60. //设置代码输出目录
  61. String projectPath = System.getProperty( "user.dir");
  62. gc.setOutputDir(projectPath + projectName + generateTo);
  63. //作者
  64. gc.setAuthor(author);
  65. //设置时间类型为Date
  66. gc.setDateType(DateType.TIME_PACK);
  67. gc.setOpen( false);
  68. //设置Mapper.xml的BaseColumnList
  69. gc.setBaseColumnList( true);
  70. //设置Mapper.xml的BaseResultMap
  71. gc.setBaseResultMap( true);
  72. // 设置实体属性 Swagger2 注解
  73. // gc.setSwagger2(true);
  74. mpg.setGlobalConfig(gc);
  75. // 数据源配置
  76. DataSourceConfig dsc = new DataSourceConfig();
  77. dsc.setUrl(url);
  78. dsc.setDriverName(driver);
  79. dsc.setUsername(username);
  80. dsc.setPassword(password);
  81. mpg.setDataSource(dsc);
  82. // 包配置
  83. PackageConfig pc = new PackageConfig();
  84. //pc.setModuleName(scanner("模块名"));
  85. pc.setParent(parentPackage);
  86. //设置包名
  87. pc.setEntity(modelName);
  88. mpg.setPackageInfo(pc);
  89. // 自定义配置
  90. InjectionConfig cfg = new InjectionConfig() {
  91. @Override
  92. public void initMap () {
  93. // to do nothing
  94. }
  95. };
  96. // 如果模板引擎是 freemarker
  97. String templatePath = "/templates/mybatis-generator/mapper2.xml.ftl";
  98. // 如果模板引擎是 velocity
  99. // String templatePath = "/templates/mapper.xml.vm";
  100. // 自定义输出配置
  101. List<FileOutConfig> focList = new ArrayList<>();
  102. // 自定义配置会被优先输出
  103. focList.add( new FileOutConfig(templatePath) {
  104. @Override
  105. public String outputFile (TableInfo tableInfo) {
  106. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  107. return projectPath + projectName + mapperXmlPath + pc.getModuleName()
  108. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  109. }
  110. });
  111. cfg.setFileOutConfigList(focList);
  112. mpg.setCfg(cfg);
  113. // 配置模板
  114. TemplateConfig templateConfig = new TemplateConfig();
  115. // 配置自定义输出模板
  116. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  117. templateConfig.setMapper( "templates/mybatis-generator/mapper2.java");
  118. templateConfig.setEntity( "templates/mybatis-generator/entity2.java");
  119. templateConfig.setService( "templates/mybatis-generator/service2.java");
  120. templateConfig.setServiceImpl( "templates/mybatis-generator/serviceImpl2.java");
  121. templateConfig.setController( "templates/mybatis-generator/controller2.java");
  122. templateConfig.setXml( null);
  123. mpg.setTemplate(templateConfig);
  124. // 策略配置
  125. StrategyConfig strategy = new StrategyConfig();
  126. strategy.setNaming(NamingStrategy.underline_to_camel);
  127. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  128. strategy.setEntityLombokModel( true);
  129. strategy.setRestControllerStyle( true);
  130. strategy.setEntitySerialVersionUID( false);
  131. //设置controller的父类
  132. if (baseControllerClassName!= null) strategy.setSuperControllerClass(baseControllerClassName);
  133. //设置服务类的父类
  134. if (baseServiceClassName != null ) strategy.setSuperServiceImplClass(baseServiceClassName);
  135. // 写于父类中的公共字段
  136. //strategy.setSuperEntityColumns("id");
  137. strategy.setInclude(scanner( "表名,多个英文逗号分割").split( ","));
  138. strategy.setControllerMappingHyphenStyle( true);
  139. strategy.setTablePrefix( "t_", "zmall_");
  140. mpg.setStrategy(strategy);
  141. mpg.setTemplateEngine( new FreemarkerTemplateEngine());
  142. mpg.execute();
  143. }
  144. }

5.修改CodeGenerator类基本生成参数,并生成代码


  
  1. //数据库连接参数
  2. public static String driver = "com.mysql.jdbc.Driver";
  3. public static String url = "jdbc:mysql://localhost:3306/zmall?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
  4. public static String username= "root";
  5. public static String password= "123456";
  6. //父级别包名称
  7. public static String parentPackage = "com.zking.zmall";
  8. //项目名设置(如果是SpringCloud项目则需要设置,其他为""即可)
  9. public static String projectName= "/zmall-generator";
  10. //代码生成的目标路径
  11. public static String generateTo = "/src/main/java";
  12. //mapper.xml的生成路径
  13. public static String mapperXmlPath = "/src/main/resources/mapper";
  14. //控制器的公共基类,用于抽象控制器的公共方法,null值表示没有父类
  15. public static String baseControllerClassName ;
  16. //业务层的公共基类,用于抽象公共方法
  17. public static String baseServiceClassName ;
  18. //作者名
  19. public static String author = "zking";
  20. //模块名称,用于组成包名
  21. public static String modelName = "model";

注意:

  • 修改数据库连接URL中的数据库名、数据库账号和密码;

  • 修改父级别包名称

  • 修改项目名,如果是SpringCloud项目则修改,不是则默认“”

先生成

zmall_product_category,zmall_product

 此时直接运行代码生成类会报错,因为还缺少mybatis-plus的依赖

 在自动生成代码子模块添加公共模块

 此时再运行

 就可以生成了

创建商品服务子模块

1.基于Spring Initializr方式创建商品服务模块zmall-product

 2.在主模块pom.xml中加入商品服务子模块zmall-product

修改zmall-product的pom.xml


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0 </modelVersion>
  5. <parent>
  6. <groupId>com.zking.zmall </groupId>
  7. <artifactId>zmall </artifactId>
  8. <version>1.0-SNAPSHOT </version>
  9. </parent>
  10. <artifactId>zmall-product </artifactId>
  11. <dependencies>
  12. <dependency>
  13. <groupId>com.zking.zmall </groupId>
  14. <artifactId>zmall-common </artifactId>
  15. <version>1.0-SNAPSHOT </version>
  16. </dependency>
  17. </dependencies>
  18. </project>

  
  1. <modules>
  2. <module>zmall-common </module>
  3. <module>zmall-user </module>
  4. <module>zmall-generator </module>
  5. <module>zmall-product </module>
  6. </modules>

 3.配置商品服务子模块zmall-product的application.yml配置文件


  
  1. server :
  2. port : 8020
  3. spring :
  4. application :
  5. name : zmall -product
  6. datasource :
  7. #type连接池类型 DBCP,C3P0,Hikari,Druid,默认为Hikari
  8. type : com.zaxxer.hikari.HikariDataSource
  9. driver - class -name : com.mysql.jdbc.Driver
  10. url : jdbc :mysql : / /localhost : 3306 /zmall ?characterEncoding =utf8 &useSSL =false &serverTimezone =Asia /Shanghai &rewriteBatchedStatements =true
  11. username : root
  12. password : 123456
  13. freemarker :
  14. suffix : .html
  15. template -loader -path : classpath : /templates /
  16. #mybatis-plus配置
  17. mybatis -plus :
  18. #所对应的 XML 文件位置
  19. mapper -locations : classpath * : /mapper / *Mapper.xml
  20. #别名包扫描路径
  21. type -aliases -package : com.zking.zmall.model
  22. configuration :
  23. #驼峰命名规则
  24. map -underscore -to -camel -case : true
  25. #日志配置
  26. logging :
  27. level :
  28. com.zking.zmall.mapper : debug

4. 在商品服务子模块中启动类上添加

ZmallProductApplication 


  
  1. package com.zking.zmall;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan({"com.zking.zmall.mapper"})
  7. public class ZmallProductApplication {
  8. public static void main (String[] args) {
  9. SpringApplication.run(ZmallProductApplication.class, args);
  10. }
  11. }

5.将公共子模块中生成的service层代码复制到商品服务子模块zmall-product中,并删除掉非商品相关的service接口及实现类

6.创建junit实现接口测试

zmall-common模块

<!--        用于test目录下的测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

ProductServiceImplTest 


  
  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @SpringBootTest
  3. public class ProductServiceImplTest {
  4. @Autowired
  5. private IProductService productService;
  6. @Before
  7. public void setUp () throws Exception {
  8. }
  9. @After
  10. public void tearDown () throws Exception {
  11. }
  12. @Test
  13. public void queryProduct () {
  14. List<Product> list = productService.list();
  15. list.forEach(System.out::println);
  16. }
  17. }

 拿到所有的数据

二、微服务项目集成Freemarker

1.在公共模块zmall-common中引入freemarker依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2.在商品子模块zmall-product中添加首页和商品详情页面及公共资源(js/css/images)

  • 将资料目录中的《易买网网页素材.rar》解压后,将其中Index.html、Product.html和js/css/images等等添加到项目的templates和static目录下,最好请将Index.html、Product.html页面首字母改成小写

  • 导入资料目录中的common目录到项目的templates目录下

  • 将页面中的头部申明<!DOCTYPE html ....>修改成<!DOCTYPE html>(支持H5风格)

  • 在页面中通过<#include>指令引入common目录中的head.html

3.创建ProductController定义请求方法

ProductController 


  
  1. package com.zking.zmall.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.zking.zmall.model.Product;
  4. import com.zking.zmall.service.IProductService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.ui.Model;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import java.util.List;
  10. @Controller
  11. public class ProductController {
  12. @Autowired
  13. private IProductService productService;
  14. @RequestMapping("/index.html")
  15. public String index (Model model){
  16. //按照商品的销量降序排序获取销量排名Top5的商品
  17. List<Product> products = productService.list( new QueryWrapper<Product>()
  18. .orderByDesc( "hot")
  19. .last( "limit 5"));
  20. model.addAttribute( "hots",products);
  21. return "index";
  22. }
  23. @RequestMapping("/product.html")
  24. public String detail (Model model,Integer pid){
  25. //根据商品ID查询商品详情信息
  26. Product product = productService.getById(pid);
  27. model.addAttribute( "product",product);
  28. return "product";
  29. }
  30. }

运行启动类

 

4. 在index.html中绑定热门数据和product.html中绑定商品详情数据

index.html

 替换为


  
  1. <ul class="featureUL">
  2. <#--判断hots是否为空-->
  3. <#if hots??>
  4. <#--循环遍历热销商品-->
  5. <#list hots as it>
  6. <li class="featureBox">
  7. <div class="box">
  8. <div class="h_icon"> <img src="images/hot.png" width="50" height="50" /> </div>
  9. <div class="imgbg">
  10. <a href="../product.html?pid=${(it.id)!}"> <img src="${(it.fileName)!}" width="160" height="136" /> </a>
  11. </div>
  12. <div class="name">
  13. <a href="../product.html?pid=${(it.id)!}">
  14. <#-- <h2>德国进口 </h2>-->
  15. ${(it.name)!}
  16. </a>
  17. </div>
  18. <div class="price">
  19. <font><span>${(it.price)!} </span> </font> &nbsp; 26R
  20. </div>
  21. </div>
  22. </li>
  23. </#list>
  24. </#if>
  25. </ul>

product.html

 替换为


  
  1. <div class="content">
  2. <div id="tsShopContainer">
  3. <div id="tsImgS"> <a href="${(product.fileName)!}" title="Images" class="MagicZoom" id="MagicZoom"> <img src="${(product.fileName)!}" width="390" height="390" /> </a> </div>
  4. <div id="tsPicContainer">
  5. <div id="tsImgSArrL" onclick="tsScrollArrLeft()"> </div>
  6. <div id="tsImgSCon">
  7. <ul>
  8. <li onclick="showPic(0)" rel="MagicZoom" class="tsSelectImg"> <img src="images/ps1.jpg" tsImgS="images/ps1.jpg" width="79" height="79" /> </li>
  9. <li onclick="showPic(1)" rel="MagicZoom"> <img src="images/ps2.jpg" tsImgS="images/ps2.jpg" width="79" height="79" /> </li>
  10. <li onclick="showPic(2)" rel="MagicZoom"> <img src="images/ps3.jpg" tsImgS="images/ps3.jpg" width="79" height="79" /> </li>
  11. <li onclick="showPic(3)" rel="MagicZoom"> <img src="images/ps4.jpg" tsImgS="images/ps4.jpg" width="79" height="79" /> </li>
  12. <li onclick="showPic(4)" rel="MagicZoom"> <img src="images/ps1.jpg" tsImgS="images/ps1.jpg" width="79" height="79" /> </li>
  13. <li onclick="showPic(5)" rel="MagicZoom"> <img src="images/ps2.jpg" tsImgS="images/ps2.jpg" width="79" height="79" /> </li>
  14. <li onclick="showPic(6)" rel="MagicZoom"> <img src="images/ps3.jpg" tsImgS="images/ps3.jpg" width="79" height="79" /> </li>
  15. <li onclick="showPic(7)" rel="MagicZoom"> <img src="images/ps4.jpg" tsImgS="images/ps4.jpg" width="79" height="79" /> </li>
  16. </ul>
  17. </div>
  18. <div id="tsImgSArrR" onclick="tsScrollArrRight()"> </div>
  19. </div>
  20. <img class="MagicZoomLoading" width="16" height="16" src="images/loading.gif" alt="Loading..." />
  21. </div>
  22. <div class="pro_des">
  23. <div class="des_name">
  24. <p>${(product.name)!} </p>
  25. “开业巨惠,北京专柜直供”,不光低价,“真”才靠谱!
  26. </div>
  27. <div class="des_price">
  28. 本店价格: <b>¥${(product.price)} </b> <br />
  29. 消费积分: <span>28R </span>
  30. </div>
  31. <div class="des_choice">
  32. <span class="fl">型号选择: </span>
  33. <ul>
  34. <li class="checked">30ml <div class="ch_img"> </div> </li>
  35. <li>50ml <div class="ch_img"> </div> </li>
  36. <li>100ml <div class="ch_img"> </div> </li>
  37. </ul>
  38. </div>
  39. <div class="des_choice">
  40. <span class="fl">颜色选择: </span>
  41. <ul>
  42. <li>红色 <div class="ch_img"> </div> </li>
  43. <li class="checked">白色 <div class="ch_img"> </div> </li>
  44. <li>黑色 <div class="ch_img"> </div> </li>
  45. </ul>
  46. </div>
  47. <div class="des_share">
  48. <div class="d_sh">
  49. 分享
  50. <div class="d_sh_bg">
  51. <a href="#"> <img src="images/sh_1.gif" /> </a>
  52. <a href="#"> <img src="images/sh_2.gif" /> </a>
  53. <a href="#"> <img src="images/sh_3.gif" /> </a>
  54. <a href="#"> <img src="images/sh_4.gif" /> </a>
  55. <a href="#"> <img src="images/sh_5.gif" /> </a>
  56. </div>
  57. </div>
  58. <div class="d_care"> <a onclick="ShowDiv('MyDiv','fade')">关注商品 </a> </div>
  59. </div>
  60. <div class="des_join">
  61. <div class="j_nums">
  62. <input type="text" value="1" name="" class="n_ipt" />
  63. <input type="button" value="" onclick="addUpdate(jq(this));" class="n_btn_1" />
  64. <input type="button" value="" onclick="jianUpdate(jq(this));" class="n_btn_2" />
  65. </div>
  66. <span class="fl"> <a onclick="ShowDiv_1('MyDiv1','fade1')"> <img src="images/j_car.png" /> </a> </span>
  67. </div>
  68. </div>
  69. <div class="s_brand">
  70. <div class="s_brand_img"> <img src="images/sbrand.jpg" width="188" height="132" /> </div>
  71. <div class="s_brand_c"> <a href="#">进入品牌专区 </a> </div>
  72. </div>
  73. </div>

效果图:

三、SpringBoot整合微服务&gateway&nginx

gateway

 请求链路要求:客户端发送请求先经过nginx,再用nginx转至内部访问网关gateway,最后由网关服务的路由规则转发到微服务的内部服务。

整合微服务之商品服务zmall-product

在公共模块zmall-common中导入微服务相关依赖


  
  1. <!--nacos客户端-->
  2. <dependency>
  3. <groupId>com.alibaba.cloud </groupId>
  4. <artifactId>spring-cloud-starter-alibaba-nacos-discovery </artifactId>
  5. </dependency>
  6. <!--fegin组件-->
  7. <dependency>
  8. <groupId>org.springframework.cloud </groupId>
  9. <artifactId>spring-cloud-starter-openfeign </artifactId>
  10. </dependency>
  11. <!--nacos配置中心-->
  12. <dependency>
  13. <groupId>com.alibaba.cloud </groupId>
  14. <artifactId>spring-cloud-starter-alibaba-nacos-config </artifactId>
  15. </dependency>

启动nacos(该快捷方式在之前的博客中有提到怎么设置的)

 访问

 配置商品服务模块zmall-product的application.yml文件


  
  1. spring:
  2. application:
  3. name: zmall-product
  4. cloud:
  5. nacos:
  6. discovery:
  7. server-addr: localhost: 8848

 修改启动类,向nacos进行注册


  
  1. package com.zking.zmall;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  6. @EnableDiscoveryClient
  7. @SpringBootApplication
  8. @MapperScan({"com.zking.zmall.mapper"})
  9. public class ZmallProductApplication {
  10. public static void main (String[] args) {
  11. SpringApplication.run(ZmallProductApplication.class, args);
  12. }
  13. }

创建并配置网关gateway服务

1.基于Spring initializr方式创建网关模块zmall-gateway

并且将网关模块zmall-gateway和父模块进行关联

2.配置pom.xml添加nacos和gateway的依赖


  
  1. <modelVersion> 4.0 .0</modelVersion>
  2. <parent>
  3. <groupId>com.zking.zmall</groupId>
  4. <artifactId>zmall</artifactId>
  5. <version> 1.0-SNAPSHOT</version>
  6. </parent>
  7. <artifactId>zmall-gateway</artifactId>
  8. <dependencies>
  9. <!--gateway 注意 此模式不能引入starter-web -->
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-gateway</artifactId>
  13. </dependency>
  14. <!--nacos客户端-->
  15. <dependency>
  16. <groupId>com.alibaba.cloud</groupId>
  17. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.projectlombok</groupId>
  21. <artifactId>lombok</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.apache.commons</groupId>
  25. <artifactId>commons-lang3</artifactId>
  26. </dependency>
  27. </dependencies>

此时网关模块的pom依赖


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0 </modelVersion>
  5. <parent>
  6. <groupId>com.zking.zmall </groupId>
  7. <artifactId>zmall </artifactId>
  8. <version>1.0-SNAPSHOT </version>
  9. </parent>
  10. <groupId>com.zking </groupId>
  11. <artifactId>zmall-gateway </artifactId>
  12. <dependencies>
  13. <!--gateway 注意 此模式不能引入starter-web -->
  14. <dependency>
  15. <groupId>org.springframework.cloud </groupId>
  16. <artifactId>spring-cloud-starter-gateway </artifactId>
  17. </dependency>
  18. <!--nacos客户端-->
  19. <dependency>
  20. <groupId>com.alibaba.cloud </groupId>
  21. <artifactId>spring-cloud-starter-alibaba-nacos-discovery </artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.projectlombok </groupId>
  25. <artifactId>lombok </artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.apache.commons </groupId>
  29. <artifactId>commons-lang3 </artifactId>
  30. </dependency>
  31. </dependencies>
  32. </project>

3.修改启动类,向nacos进行注册


  
  1. package com.zking.zmall;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. @EnableDiscoveryClient
  6. @SpringBootApplication
  7. public class ZmallGatewayApplication {
  8. public static void main (String[] args) {
  9. SpringApplication.run(ZmallGatewayApplication.class, args);
  10. }
  11. }

4.配置application.yml设置gateway路由转发规则

server:
  port: 8000
spring:
  application:
    name: zmall-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      routes:
        - id: product_route
          uri: lb://zmall-product # lb指的是从nacos中按照名称获取微服务,并遵循负载均衡策略
          predicates:
            - Path=/product-serv/**
          filters:
            - StripPrefix=1

 5.将易买网网页素材中的公共静态资源js/css/images复制到gateway网关服务中

这里请注意了,之前在商品服务模块zmall-product中已经配置了易买网的静态资源,为什么还要在gateway网关服务中再配置一次呢?这是因为当请求经过gateway网关服务后会进行断言条件匹配和条件路径截取等操作,从而导致gateway网关路由转发后静态资源失效404的问题,所以特此在gateway网关服务中也配置一次易买网网页素材中的公共静态资源js/css/images,确保能正常访问

解决方案:(使用nginx动静分离方式实现) 配置静态资源访问服务器,将各个微服务模块中的静态访问资源迁移到静态资源访问服务器中,然后通过http方式访问即可。

 在gateway网关服务中配置一次易买网网页素材中的公共静态资源js/css/images

  在gateway网关服务中配置一次易买网网页素材中的公共静态资源js/css/images

 

 

 

安装配置Windows版nginx

1.解压nginx-1.18.0.zip至任意目录

下载安装包

 

双击 以上红框 就可以访问到nginx了

确保nginx是能用的 然后关掉进程 进行配置

 此时就访问不到了

 2.进入conf目录,并修改nginx.conf配置文件

server
{
    listen 80;
    server_name zmall.com;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    location / {
        proxy_pass http://127.0.0.1:8000/;
    }
}

安装配置SwitchHosts

1.直接双击exe文件即可安装SwitchHosts

 桌面就有这个

2. 打开SwitchHosts设置一级域名

出现这种情况

 就用管理员身份运行

 

 再次启动nginx(最后运行nginx根目录下的nginx.exe启动nginx )

如果出现IIS7,那么cmd窗口中执行下列指令

net stop w3svc

请求链路测试

单独访问商品服务:http://localhost:8020/index.html

通过gateway访问:http://localhost:8000/product-serv/index.html

通过nginx访问:http://zmall.com/product-serv/index.html

 单独访问商品服务

 通过gateway访问

 通过nginx访问

 


转载:https://blog.csdn.net/weixin_62735525/article/details/128890359
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场