谷粒商城遇到的bug

版本说明

GitHub:版本说明spring-cloud-alibaba

本次项目使用2021.x 分支:

Spring Cloud Alibaba VersionSpring Cloud VersionSpring Boot Version
2021.0.4.0Spring Cloud 2021.0.42.6.11

p18 单元测试报错:

java.lang.IllegalStateException: Failed to load ApplicationContext

Error creating bean with name ‘attrAttrgroupRelationController’: Unsatisfied dependency expressed through field ‘attrAttrgroupRelationService’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘attrAttrgroupRelationService’: Unsatisfied dependency expressed through field ‘baseMapper’; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘attrAttrgroupRelationDao’ defined in file [C:\Users\admin.m2\repository\org\springframework\boot\spring-boot-starter-parent\2.7.6\target\classes\com\atguigu\gulimall\product\dao\AttrAttrgroupRelationDao.class]: Unsatisfied dependency expressed through bean property ‘sqlSessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sqlSessionFactory’ defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method ‘sqlSessionFactory’ threw exception; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/classpath*:/mapper/**/*.xml]

Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method ‘sqlSessionFactory’ threw exception; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/classpath*:/mapper/**/*.xml]

单元测试类中,老师使用了RunWith注解
这个是junit4的,高版本springboot中已经不再使用,需要使用
@SpringBootTest(classes = GulimallProductApplication.class)

p21 Nacos启动错误

启动闪退

  1. 没有配置环境变量(排除)
  2. NACOS2默认启动是集群模式,应将其换为单体模式。
startup.cmd -m standalone

启动报错

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'basicAuthenticationFilter' defined in class path resource
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'nacosAuthConfig' defined in URL
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'tokenManagerDelegate'
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jwtTokenManager' defined in URL
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate
...
Caused by: java.lang.IllegalArgumentException: the length of secret key must great than or equal 32 bytes; And the secret key  must be encoded by base64.Please see https://nacos.io/zh-cn/docs/v2/guide/user/auth.html
...
Caused by: java.lang.IllegalArgumentException: The specified key byte array is 0 bits which is not secure enough for any JWT HMAC-SHA algorithm

Base64编码/解码器,在线解码Base64 (sojson.com)
修改application.properties

# 使用zxldenacosserverstartuplocaltest转换为base64
nacos.core.auth.plugin.nacos.token.secret.key=enhsZGVuYWNvc3NlcnZlcnN0YXJ0dXBsb2NhbHRlc3Q=

nacos官方文档:Authorization (nacos.io)
github上的相关问题:从最新发布2.2.0.1的版本中直接启动报错 · Issue #10047 · alibaba/nacos · GitHub

p22 member启动报错

member引入 srpingcloud openfeign 项目启动报错

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'memberController': Unsatisfied dependency expressed through field 'couponFeignService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.atguigu.gulimall.member.feign.CouponFeignService': Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?

由于Spring Cloud Feign在Hoxton.M2 RELEASED版本之后不再使用Ribbon而是使用spring-cloud-loadbalancer,所以不引入spring-cloud-loadbalancer会报错.
参考:Java项目《谷粒商城》Java架构师 | 微服务 | 大型电商项目 - 哔哩哔哩 (bilibili.com)

  1. nacos中排除ribbon依赖
  2. 引入 spring-cloud-loadbalancer

实操:
common的pom.xml

<!--nocas-->  
<dependency>  
	<groupId>com.alibaba.cloud</groupId>  
	<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>  
	<exclusions>
		<exclusion>  
			<groupId>org.springframework.cloud</groupId>  
			<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>  
		</exclusion>  
	</exclusions>  
</dependency>

member的pom.xml

<!--解决:Did you forget to include spring-cloud-starter-loadbalancer?-->  
<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-loadbalancer</artifactId>  
</dependency>

p23 nacos配置中心启动报错

create config service error!properties=NacosConfigProperties{serverAddr='null', encode='null', group='DEFAULT_GROUP', prefix='null', fileExtension='properties', timeout=3000, endpoint='null', namespace='null', accessKey='null', secretKey='null', contextPath='null', clusterName='null', name='null', sharedDataids='null', refreshableDataids='null', extConfig=null},e=,

SpringBoot 2.4.x的版本之后,对于bootstrap.properties/bootstrap.yaml配置文件(我们合起来成为Bootstrap配置文件)的支持,需要导入如下的依赖

<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-bootstrap</artifactId>  
    <version>3.1.6</version>  
</dependency>

p46 renren-fast注册到nacos

报错1

注册失败,新版本配置中心,必须配置,缺少配置无法启动。

报错2

java.lang.NoSuchMethodError: com.google.common.collect.Sets$SetView.iterator()Lcom/google/common/collect/UnmodifiableIterator;

缺少依赖:

<dependency>  
   <groupId>com.google.guava</groupId>  
   <artifactId>guava</artifactId>  
   <version>30.1-jre</version>  
</dependency>

p46 路径重写无效

排查过程

  1. 先debug查看重写后的地址,参考SpringCloud的GateWay网关中怎么debug得到真实的路由地址

  2. 得到lb://renren-fast/renren-fast/captcha.jpg?uuid=c912b48e-c1fb-4c33-836c-0f96d026392c

  3. 进入nacos服务列表查看renren-fast
    在这里插入图片描述

  4. 发现使用ip替换renren-fast 可以访问,推断时lb://导致

  5. csdn找到参考:[Nacos+Gateway使用lb: xxxservice不起作用](Nacos+Gateway使用lb: xxxservice不起作用_呦呦鹿铭的博客-优快云博客)

  6. 参考2:Spring cloud loadbalancer跟Nacos进行整合

  7. gulimall-commonpom.xml中添加依赖

<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>  
    <version>2.2.1.RELEASE</version>  
</dependency>	
  1. 启动发现renren-fastloadbalancer包冲突
  2. 移除renren-fast的common依赖
  3. 单独引入
<!--nacos服务注册/发现-->  
<dependency>  
   <groupId>com.alibaba.cloud</groupId>  
   <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>  
   <version>2021.0.4.0</version>
   <exclusions>      
	   <exclusion>  
         <groupId>org.springframework.cloud</groupId>  
         <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>  
      </exclusion>  
   </exclusions>  
</dependency>  
<!--   nacos配置中心     -->  
<dependency>  
   <groupId>com.alibaba.cloud</groupId>  
   <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>  
   <version>2021.0.4.0</version>
</dependency>	
  1. 重启发现验证码可以加载

在这里插入图片描述

renren-fast maven报错

'parent.relativePath' of POM io.renren:renren-generator:1.0.0 (E:\Gitee\gulimall\renren-generator\pom.xml) points at com.atguigu.gulimall:gulimall instead of org.springframework.boot:spring-boot-starter-parent, please verify your project structure

参考:解决Maven ‘parent.relativePath‘ of POM_BingTaiLi的博客-优快云博客
方法:

<parent>  
   <groupId>org.springframework.boot</groupId>  
   <artifactId>spring-boot-starter-parent</artifactId>  
   <version>2.6.11</version>  
   <relativePath></relativePath>
</parent>

p47 跨域配置后依旧报错

Access to XMLHttpRequest at 'http://localhost:88/api/sys/login' from origin 'http://localhost:8001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

报错原因:Not possible to use allowedOrigins “*” in StompEndpointRegistry after upgrade to Spring Boot 2.4.0 · Issue #26111 · spring-projects/spring-framework · GitHub
spring boot2.4版本之后提供了allowedOriginPatterns方法供使用。原本的allowCredentials为true时,allowedOrigins不能使用 * 号匹配
修改为:

@Bean  
public CorsWebFilter corsWebFilter() {  
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
    CorsConfiguration corsConfiguration = new CorsConfiguration();  
  
    // 1.配置跨域  
    corsConfiguration.addAllowedHeader("*");  
    corsConfiguration.addAllowedMethod("*");  
    corsConfiguration.addAllowedOriginPattern("*");  
    corsConfiguration.setAllowCredentials(true);//是否允许携带cookie  
  
    source.registerCorsConfiguration("/**", corsConfiguration);  
    return new CorsWebFilter(source);  
}

p48没有发送tree请求

created()和methods()是平级的

methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        this.menus = data.data;
      }).catch(() => {});
    }
  },
  created() {
    this.getMenus();
  }

p53新增的三级菜单不显示

参考:Long型和long型的比较大小及==和equals()
Long是引用数据类型,当其数值在[-128,127]之间时,能用==判断是否相等,亦可用 >、< 比较大小。

@TableId  
private Long catId;
private Long parentCid;

原因:java.lang.Long.java中:

private static class LongCache {
	private LongCache(){}

	static final Long cache[] = new Long[-(-128) + 127 + 1];

	static {
		for(int i = 0; i < cache.length; i++)
			cache[i] = new Long(i - 128);
	}
}

LongCache会预先缓存 [-128,127] 范围内的数,通过缓存频繁请求的值代来更好的空间和时间性能,当数据超出此范围,则new一个Long对象;

新增的数据明显超过了127,所以在categoryEntity.getParentCid()等于root.getCatId()的判断时为false,应该使用longValue()比较真实的值

private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {  
    List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().longValue() == root.getCatId().longValue()).map(categoryEntity -> {  
        categoryEntity.setChildren(getChildren(categoryEntity, all));  
        return categoryEntity;  
    }).sorted(Comparator.comparingInt(m -> (m.getSort() == null ? 0 : m.getSort()))).collect(Collectors.toList());  
    return children;  
}

p62-63 阿里云OSS相关

详见:Alibaba Cloud OSS

p64 请求403错误

//资料提供的
_self.dataObj.ossaccessKeyId = response.data.accessid;
//后台返回的
_self.dataObj.ossaccessKeyId = response.data.accessId;

p66 @NotBlank等注解爆红

<!--高版本boot需要引入以下包,放到common中-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
	<version>2.6.11</version>
</dependency>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值