微服务SpringCloud报错合集

温馨提示:程序报错往往千奇百怪,本文仅记录笔者遇到的报错与解决方案,不对任何人负责!

一、springcloud gateway + nacos 遇到503错误

本节介绍了如何在Spring Cloud Gateway中集成Nacos客户端和Feign组件,以解决服务发现和负载均衡问题。通过添加Feign依赖并配置,解决了503服务不可用的报错,重点在于Nacos与Feign的兼容性和Feign的负载均衡功能。

pom文件依赖

复制代码
<dependencies>
        <!--nacos客户端-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--gateway网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

主类加入服务发现注解

java 复制代码
package com.gateway;

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

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

配置yml

复制代码
server:
  port: 7000
spring:
  application:
    name: service-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: product_route
          uri: lb://service-product
          predicates:
            - Path=/product-serv/**
          filters:
            - StripPrefix=1

测试报错

报503错误,原因是微服务不可获取

解决:加入feign依赖

复制代码
<dependencies>
        <!--nacos客户端-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--fegin组件-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- Feign Client for loadBalancing -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
            <version>3.0.2</version>
        </dependency>
        <!--gateway网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

重启测试:OK

二、springcloud-alibaba feign整合sentinel 报不满足依赖错误

本节介绍了在Spring Cloud项目中整合Sentinel时遇到的Feign客户端问题,详细展示了因为@EnableFeignClients注解扫描包配置不正确导致的依赖注入失败。通过指定扫描@FeignClient所在包路径解决了问题,同时实现了微服务间的容错逻辑。当商品微服务关闭时,订单微服务能够进入容错逻辑返回默认值。在解决过程中,还涉及了版本升级和错误排查,最终实现了Sentinel的完整集成。

错误描述

在feign整合sentinel时遇到了一个问题,折腾了一天,发现是@EnableFeignClients扫包的问题

具体错误:

复制代码
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.yushanma.service.ProductService': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1415) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:608) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:923) ~[spring-context-5.3.3.jar:5.3.3]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:588) ~[spring-context-5.3.3.jar:5.3.3]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:767) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:426) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1311) ~[spring-boot-2.4.2.jar:2.4.2]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1300) ~[spring-boot-2.4.2.jar:2.4.2]
	at com.yushanma.TestApplication.main(TestApplication.java:21) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.yushanma.service.ProductService': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
	at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:176) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1884) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1268) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:267) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.addCandidateEntry(DefaultListableBeanFactory.java:1605) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1562) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1343) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.3.jar:5.3.3]
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.3.jar:5.3.3]
	... 20 common frames omitted
Caused by: java.lang.NullPointerException: null
	at com.alibaba.cloud.sentinel.feign.SentinelFeign$Builder$1.create(SentinelFeign.java:92) ~[spring-cloud-starter-alibaba-sentinel-2020.0.RC1.jar:2020.0.RC1]
	at feign.ReflectiveFeign.newInstance(ReflectiveFeign.java:64) ~[feign-core-10.10.1.jar:na]
	at feign.Feign$Builder.target(Feign.java:269) ~[feign-core-10.10.1.jar:na]
	at org.springframework.cloud.openfeign.DefaultTargeter.target(DefaultTargeter.java:30) ~[spring-cloud-openfeign-core-3.0.0.jar:3.0.0]
	at org.springframework.cloud.openfeign.FeignClientFactoryBean.loadBalance(FeignClientFactoryBean.java:306) ~[spring-cloud-openfeign-core-3.0.0.jar:3.0.0]
	at org.springframework.cloud.openfeign.FeignClientFactoryBean.getTarget(FeignClientFactoryBean.java:335) ~[spring-cloud-openfeign-core-3.0.0.jar:3.0.0]
	at org.springframework.cloud.openfeign.FeignClientFactoryBean.getObject(FeignClientFactoryBean.java:315) ~[spring-cloud-openfeign-core-3.0.0.jar:3.0.0]
	at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:169) ~[spring-beans-5.3.3.jar:5.3.3]
	... 31 common frames omitted


Process finished with exit code 1

虽然用了@EnableFeignClients注解,但是在微服务多模块项目中也扫不到@FeignClient注解的类,这个类没有生成实例,在controller中@Autowire就没有办法注入依赖,最后报不满足依赖的错误。

解决方法

解决方法:指定扫描@FeignClient所在的包路径

java 复制代码
package com.yushanma;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication//(scanBasePackages = {"com.yushanma.service","com.yushanma.controller"})
//@EnableDiscoveryClient
@EnableFeignClients(basePackages="com.yushanma.fallback")
//@EnableFeignClients
//@SpringCloudApplication
@MapperScan("com.pojo.mapper")
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class);
    }
}

关闭商品微服务后,订单微服务进入容错逻辑

完整代码

java 复制代码
package com.yushanma.service;

//Product product =
//        restTemplate.getForObject("http://" + url + "/product/" + pid, Product.class);


import com.pojo.model.Product;
import com.yushanma.config.FeignConfiguration;
import com.yushanma.fallback.EchoServiceFallback;
import com.yushanma.fallback.EchoServiceFallbackFactory;
import com.yushanma.fallback.ProductServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Primary;
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.RequestMethod;

@FeignClient(
        name = "service-product",
//        fallback = ProductServiceFallback.class
//        fallbackFactory = ProductServiceFallBackFactory.class
        fallbackFactory = EchoServiceFallbackFactory.class,
        primary = true
//        fallback = EchoServiceFallback.class,
//        configuration = FeignConfiguration.class
)

public interface ProductService {

    //@FeignClient+@GetMapping 就是一个完整的请求路径 http://service-product/product/{pid}
    @RequestMapping(method = RequestMethod.GET, value = "/product/{pid}")
    Product findByPid(@PathVariable("pid") Integer pid);
}
java 复制代码
package com.yushanma.fallback;

import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class EchoServiceFallbackFactory implements FallbackFactory<EchoServiceFallback> {

    @Override
    public EchoServiceFallback create(Throwable throwable) {
        return new EchoServiceFallback(throwable);
    }

}
java 复制代码
package com.yushanma.fallback;

import com.pojo.model.Product;
import com.yushanma.service.ProductService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EchoServiceFallback implements ProductService {
    private Throwable throwable;

    EchoServiceFallback(Throwable throwable) {
        this.throwable = throwable;
    }

    @Override
    public Product findByPid(Integer pid) {
        Product product = new Product();
        product.setPid(-1);
        product.setPname("product-service调用出错,进入容错逻辑");
//        log.info("{}",throwable.getMessage());
        return product;
    }
}
java 复制代码
package com.yushanma.controller;

import com.alibaba.fastjson.JSON;
import com.pojo.model.Order;
import com.pojo.model.Product;
import com.yushanma.service.OrderService;
import com.yushanma.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class ProductController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    //  基于Ribbon实现负载均衡
    @RequestMapping("order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("查询商品{}", pid);
        Product product = productService.findByPid(pid);
        //容错处理
        if (product.getPid() == -1) {
            Order order = new Order();
            order.setPname("下单失败");
            return order;

        }
        log.info("查询到的商品信息为{}", JSON.toJSONString(product));
        Order order = new Order();
        order.setUid(1);
        order.setUsername("yushanma");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
//        orderService.createOrder(order);
        log.info("创建新的订单{}", JSON.toJSONString(order));
        return order;
    }
}

后续问题与解决

但是出现后续问题:无论商品微服务是否开启,订单微服务一直进入容错逻辑

发现是(basePackages="com.yushanma.fallback")的问题,应指定为"com.yushanma.service",但还是报空指针错误。最终考虑更换父工程版本:

复制代码
    <!--    父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </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-cloud.version>Hoxton.SR8</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.5.RELEASE</spring-cloud-alibaba.version>
    </properties>

去掉feign的版本指定:

复制代码
        <!--fegin组件-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- Feign Client for loadBalancing -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

不需再指定扫包:

开启两个服务后:请求下单成功

关闭商品微服务后下单:进入容错逻辑

至此,feign整合sentinel完成。

参考:

https://www.cnblogs.com/keeya/p/14476548.html

https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/#spring-cloud-feign-overriding-defaults

https://segmentfault.com/a/1190000018914017

https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example

相关推荐
Zz_waiting.3 小时前
统一服务入口-Gateway
java·开发语言·gateway
一 乐3 小时前
流浪动物救助|流浪猫狗救助|基于Springboot+vue的流浪猫狗救助平台设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设
爱宇阳3 小时前
Spring Boot 项目 GitLab CI/CD 自动构建并推送到 Harbor 教程
spring boot·ci/cd·gitlab
L.EscaRC4 小时前
面向 Spring Boot 的 JVM 深度解析
jvm·spring boot·后端
老华带你飞4 小时前
订票系统|车票管理系统|基于Java+vue的车票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·订票系统
陈果然DeepVersion4 小时前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(十一)
java·spring boot·微服务·ai·kafka·面试题·rag
whltaoin5 小时前
【浏览器CORS问题解决方案】SpringBoot+Vue3前后端全覆盖:浏览器跨域问题的多样化解决方案
vue.js·spring boot·浏览器跨域问题
Mos_x5 小时前
【Spring Boot】Spring Boot解决循环依赖
java·spring boot·spring
亚林瓜子6 小时前
AWS Elastic Beanstalk中安装tesseract5.3.4版本
spring boot·ocr·tesseract·aws·beanstalk·tess4j·eb