会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 133532个问题

manager.py

from  flask_shop import create_app,db
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager

app = create_app('develop')

manager = Manager(app)  
Migrate(app,db) #将app和db绑定到flask—migrate
manager.add_command('db',MigrateCommand)    #添加Migrate的所有子命令到db下

if __name__ == 'main':
    app.run()

__init__.py(flask_shop)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config_map

db = SQLAlchemy()   
def create_app(config_name):   
    app = Flask(__name__)
    obj = config_map.get(config_name)
    app.config.from_object(obj) 
    db.init_app(app)    

    
    from flask_shop.user import user    #注册蓝图
    app.register_blueprint(user)
    return app


if __name__=='__main__':
    app.run()

config.py

import os

class Config:
    # 配置mysql参数
    MYSQL_DIALECT = 'mysql'
    MYSQL_DRIVER = 'pymysql'
    MYSQL_NAME = 'root'
    MYSQL_PWD = 'root'
    MYSQL_HOST = '127.0.0.1'
    MYSQL_PORT = '3306'
    MYSQL_DB = 'shop_env'
    MYSQL_CHARSET = 'utf8mb4'

    SQLARCHEMY_DATABASE_URL = f'{MYSQL_DIALECT}+{MYSQL_DRIVER}://{MYSQL_NAME}:{MYSQL_PWD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}?charset={MYSQL_CHARSET} '
    SQLARCHEMY_TRACK_MODIFICATIONS  = True


    SECRET_KEY = os.urandom(16)  #加盐

class DevelopmentConfig(Config):    #开发者模式,开启DEBUG
    DEBUG = True
class ProductionConfig(Config):     #生产者模式,不用开启DEBUG
    pass

config_map = {
    'develop':DevelopmentConfig,
    'product':ProductionConfig
}

报错

                         & D:/python/python.exe d:/python/flask_shop/flask_shop/__init__.py

Traceback (most recent call last):

  File "d:/python/flask_shop/flask_shop/__init__.py", line 3, in <module>

    from config import config_map

ModuleNotFoundError: No module named 'config'

PS D:\python\flask_shop>

为什么提示找不到config呢?

Python 全系列/第九阶段:Flask百战电商后台系统/Flask百战电商后台项目 32701楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 32702楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 32706楼
WEB前端全系列/第十九阶段:Vue2知识体系(旧)/Vue基础知识 32707楼
JAVA 全系列/第四阶段:数据库与AI协同技术实战/SQL 语言 32708楼

Ribbon 实现负载均衡的编码有两种方式:

1、通过在 RestTemplate 上配置注解 @LoadBalanced;

2、通过类 RibbonLoadBalancerClient 的 choose() 方法实现。我看资料上 RibbonLoadBalancerClient 这个类是可以自动注入的,并且我在测试类中也实现了自动注入的调用:

package cn.edu.hyit.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest()
public class LoadBalanceTest {

    @Autowired
    RibbonLoadBalancerClient client;

    @Test
    public void test(){
        for (int i = 0; i < 10; i++) {
            ServiceInstance instance = this.client.choose("user-service");
            System.out.println(instance.getHost() + ":" + instance.getPort());
        }
    }
}

结果为:

image.png

但是当我在 controller 中对 RibbonLoadBalancerClient 这个类进行自动注入时,会报错,代码如下:

package cn.edu.hyit.user.controller;

import cn.edu.hyit.user.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("usercontroller")
@Slf4j
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RibbonLoadBalancerClient ribbonLoadBalancerClient;

    @RequestMapping("findByIdByRibbon2/{id}")
    public User findByIdByRibbon2(@PathVariable("id") Integer id) {
        log.debug("findByIdByRibbon Method is Running...");

        ServiceInstance serviceInstance = ribbonLoadBalancerClient.choose("user-service");
        String url = "http://"+ serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/usercontroller/" + id;
        System.out.println(url);
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}

报错如下:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]

at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]

at cn.edu.hyit.ConsumerApplication.main(ConsumerApplication.java:14) [classes/:na]


2020-05-14 15:22:12.532 ERROR 13804 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 


***************************

APPLICATION FAILED TO START

***************************


Description:


Field ribbonLoadBalancerClient in cn.edu.hyit.user.controller.UserController required a bean of type 'org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient' that could not be found.



Action:


Consider defining a bean of type 'org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient' in your configuration.

使用的 Spring Cloud 的版本为 Finchley.SR1。

请帮忙看看这个报错,谢谢!


JAVA 全系列/第二十阶段:Spring Cloud微服务技术栈/Spring Cloud(旧) 32710楼
Python 全系列/第十六阶段:Python 爬虫开发/爬虫基础(旧) 32712楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 32713楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/常用类 32714楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637