def register(): eureka_client.init( eureka_server=EUREKA_SERVER, app_name=os.getenv("APP_NAME"), instance_host=os.getenv("APP_HOST_OUT"), instance_port=int(os.getenv("APP_PORT_OUT")), )
def connect_eureka(ip, port): eureka_client.init( eureka_server=CONFIG['eureka.client.serviceUrl.defaultZone'], app_name="matrix", instance_host=ip, instance_port=port, ha_strategy=eureka_client.HA_STRATEGY_OTHER)
async def init_client(eureka_url: str = None, application_name: str = None, instance_port: int = None, instance_id: str = None, instance_host: str = None, instance_ip: str = None): """ The flowing code will register your server to eureka server and also start to send heartbeat every 30 seconds :param eureka_url: str -> The URL of the Eureka server :param application_name: str -> The application name :param instance_port: int -> The instance port :param instance_id: str -> The instance id :param instance_host: str -> The instance host :param instance_ip: str -> The instance ip :return: """ try: eureka_url = internal_get_config(eureka_url, "Eureka URL", "EUREKA_URL", True) application_name = internal_get_config(application_name, "Application name", "APP_NAME", True) instance_port = internal_get_config(instance_port, "instance port given", "APP_PORT", False, int) except ValueError as e: log.error(f"Error when starting Eureka. Lack of parameter: {str(e)}") return False if not instance_id: instance_id = f"{application_name}:{generate_nonce(21)}" log.warning(f"Not instance id given. Will use {instance_id}") if not instance_host: instance_host = internal_get_config(None, "Domain name", "DOMAIN_NAME", False) or "" log.info(f"Registering {application_name} to Eureka: {eureka_url}") eureka_client.init(eureka_server=eureka_url, app_name=application_name, instance_port=instance_port, instance_id=instance_id, instance_host=instance_host, ha_strategy=eureka_client.HA_STRATEGY_STICK)
def main(): tornado.options.parse_command_line() # 注册eureka服务 eureka_client.init(eureka_server="http://localhost:9000/eureka/", app_name="python-service", instance_port=3333) app = tornado.web.Application(handlers=[(r"/predict", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
def setEureka(): server_host = "192.168.1.100" server_port = 5000 eureka_client.init(eureka_server="http://192.168.0.130:8761/eureka", app_name="flask_server2", # 当前组件的主机名,可选参数,如果不填写会自动计算一个,如果服务和 eureka 服务器部署在同一台机器,请必须填写,否则会计算出 127.0.0.1 # instance_host=server_host, instance_port=server_port, # 调用其他服务时的高可用策略,可选,默认为随机 ha_strategy=eureka_client.HA_STRATEGY_RANDOM)
def setEureka(): server_host = "localhost" server_port = 9004 eureka_client.init( eureka_server="http://localhost:5000/eureka", app_name="service-movie", # 当前组件的主机名,可选参数,如果不填写会自动计算一个,如果服务和 eureka 服务器部署在同一台机器,请必须填写,否则会计算出 127.0.0.1 instance_host=server_host, instance_port=server_port, # 调用其他服务时的高可用策略,可选,默认为随机 ha_strategy=eureka_client.HA_STRATEGY_RANDOM)
def regist(): eureka_client.init(eureka_server=eureka_server, app_name=app_name, instance_port=instance_port) handlers = [] handlers.append(('/findAllUsers', UserHandler)) handlers.append(('/processUserContent', WordsHandler)) handlers.append(('/recognize', ImageHandler)) app = tornado.web.Application(handlers=handlers) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(client_port) tornado.ioloop.IOLoop.instance().start()
def startup_installed(sender): import py_eureka_client.eureka_client as eureka_client # 提供给py_eureka_client使用 eureka_client.init( eureka_server=settings.EUREKA.eureka_server, app_name=settings.EUREKA.app_name, # 当前组件的主机名,可选参数,如果不填写会自动计算一个,如果服务和 eureka 服务器部署在同一台机器,请必须填写,否则会计算出 127.0.0.1 instance_host=settings.EUREKA.server_host, instance_port=settings.EUREKA.server_port, # 调用其他服务时的高可用策略,可选,默认为随机 ha_strategy=settings.EUREKA.ha_strategy)
def setEureka(): server_host = conf.SERVER_CONFIG['host'] server_port = int(conf.SERVER_CONFIG['port']) eureka_client.init( eureka_server="http://modderbug.cn:8080/eureka/", app_name="tfhub_server", # 当前组件的主机名,可选参数,如果不填写会自动计算一个,如果服务和 eureka 服务器部署在同一台机器,请必须填写,否则会计算出 127.0.0.1 instance_host=server_host, instance_port=server_port, # 调用其他服务时的高可用策略,可选,默认为随机 # ha_strategy=eureka_client.HA_STRATEGY_RANDOM )
def init_eureka(): if EUREKA_URL: try: eureka_client.init(eureka_server=EUREKA_URL, app_name="marketplace-service", instance_host="localhost", instance_port=MARKETPLACE_PORT, status_page_url="/actuator/info", health_check_url="/actuator/health", home_page_url="/ui") ExternalServices.eureka_on = True except Exception as e: print(e) ExternalServices.eureka_on = False
def eurekaclient(): tornado.options.parse_command_line() #注册eureka服务 eureka_client.init( eureka_server="http://127.0.0.1:8502/eureka/", app_name=options.appName, instance_port=options.port, # 调用其他服务时的高可用策略,可选,默认为随机 ha_strategy=eureka_client.HA_STRATEGY_RANDOM, data_center_name='MyOwn') app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() print("eureka exec")
def execute_register(): client_init = eureka_client.init( eureka_server="http://127.0.0.1:8761/eureka", app_name="Django", instance_host=server_host, instance_port=server_port, ha_strategy=eureka_client.HA_STRATEGY_RANDOM)
def setEureka(): ''' 设置eureka :param :return: ''' server_host = "localhost" server_port = 8050 eureka_client.init( eureka_server="http://localhost:8761/eureka/", app_name="microservice-maintain", # 当前组件的主机名,可选参数,如果不填写会自动计算一个,如果服务和 eureka 服务器部署在同一台机器,请必须填写,否则会计算出 127.0.0.1 instance_host=server_host, instance_port=server_port, # 调用其他服务时的高可用策略,可选,默认为随机 ha_strategy=eureka_client.HA_STRATEGY_RANDOM)
def registry(): # no spaces or underscores, this needs to be url-friendly service_name = 'budget' # This needs to be an IP accessible by anyone that # may want to discover, connect and/or use your service. ip = 'budget' #'127.0.0.1' port = 5000 home_page_url = 'manage/info' manage_health_path = 'manage/health' eureka_url = "http://%s:%s/eureka" % ( os.environ['EUREKA_HOST'], os.environ['EUREKA_PORT'] ) #http://discovery:8761/eureka your_rest_server_port = 5000 try: sleep(15) registry_client, discovery_client = eureka_client.init( eureka_server=eureka_url, app_name=service_name, instance_ip=ip, instance_port=your_rest_server_port) registry_client.send_heart_beat() except Exception as e: return registry()
def register_app(self, app_ip_port, app_append_label): app_ip = app_ip_port.split(":")[0] app_port = int(app_ip_port.split(":")[1]) print("Starting eureka register on eureka server " + self.host + ".\n") print(properties['name'] + " registering with: ip=" + app_ip + ", port=" + str(app_port) + "... \n") protocol = "https" if EnvStartupSingleton.get_instance().get_config_env_vars().get(EnvConstants.HTTPS_ENABLE) \ else "http" eureka_client.init(eureka_server=f"{self.host}", app_name=f"{properties['name']}{app_append_label}", instance_port=app_port, instance_secure_port=app_port, instance_ip=app_ip, home_page_url=f"{protocol}://{app_ip}:{app_port}/{EnvInit.init.get(EnvConstants.DEPLOY_WITH)}/", health_check_url=f"{protocol}://{app_ip}:{app_port}/{EnvInit.init.get(EnvConstants.DEPLOY_WITH)}/ping", status_page_url=f"{protocol}://{app_ip}:{app_port}/{EnvInit.init.get(EnvConstants.DEPLOY_WITH)}/about" )
def connectEureka(config, port): ##Eureka configuration eureka_server = None if config.has_option("app", Constants.EUREKA_SERVER) != False: eureka_server = config["app"][Constants.EUREKA_SERVER] if environ.get(Constants.EUREKA_SERVER): eureka_server = environ.get(Constants.EUREKA_SERVER) if eureka_server == None: raise Exception("Eureka is not define!") else: try: eureka_client.init(eureka_server=eureka_server, app_name="Notification", instance_port=int(port)) except: raise Exception("Fail to Connect to Eureka")
def register_app(self, app_ip, app_port): print("Starting eureka register on eureka server {}. \n".format( self.host)) print("{} registering with: ip={}, port={} \n".format( properties['name'], app_ip, app_port)) protocol = "https" if EnvStartupSingleton.get_instance().get_config_env_vars().get(EnvConstants.HTTPS_ENABLE) \ else "http" eureka_client.init( eureka_server=f"{self.host}", app_name=f"{properties['name']}", instance_port=app_port, instance_secure_port=app_port, instance_ip=app_ip, home_page_url=f"{protocol}://{app_ip}:{app_port}/", health_check_url=f"{protocol}://{app_ip}:{app_port}/ping", status_page_url=f"{protocol}://{app_ip}:{app_port}/ping")
def initialize_spring_cloud_client(app): server_port = app.config['SERVER_PORT'] # The following code will register server to eureka server and also start to send heartbeat every 30 seconds eureka_client.init(eureka_server=app.config['EUREKA_SERVER'], app_name="python-service", instance_port=server_port) address = app.config["SPRING_CLOUD_CONFIG_URI"] profile = app.config['SPRING_PROFILES_ACTIVE'] app_name = app.config['APP_NAME'] config_client = spring.ConfigClient( app_name=app_name, url="{address}/{app_name}/{profile}.json", profile=profile, branch=None, address=address) config_client.url = config_client.url[:-5] config_client.get_config( headers={'X-Encrypt-Key': app.config['X_ENCRYPT_KEY']}) if profile != 'prod': try: jwt_secret = config_client.config['propertySources'][0]['source'][ 'security.oauth2.resource.jwt.keyValue'] except Exception: jwt_secret = config_client.config['propertySources'][1]['source'][ 'security.oauth2.resource.jwt.keyValue'] log.debug('Jwt Secret: %s', jwt_secret) app.config['JWT_SECRET_KEY'] = base64.b64decode(jwt_secret) app.config['SECRET_KEY'] = app.config['JWT_SECRET_KEY'] else: app.config['JWT_PUBLIC_KEY'] = open(app.config['JWT_PUBLIC_KEY'], "r").read() log.debug('Config environment: %s', app.config) # provide app's version and deploy environment/config name to set a gauge metric register_metrics(app, app_version="v0.1.2", app_config="staging")
def main(): your_rest_server_port = 8000 eureka_client.init(eureka_server="http://34.66.153.219:8761/eureka/", app_name="LOCATION-SERVICE", instance_port=your_rest_server_port, instance_ip="35.225.198.249" ) # eureka_client.init_registry_client(eureka_server="http://34.66.153.219:8761/eureka/", # app_name="LOCATION_SERVICE") # eureka_client.stop() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv)
def register_app(self, app_ip_port): app_ip = app_ip_port.split(":")[0] app_port = int(app_ip_port.split(":")[1].split("/")[0]) pre_url = "/".join(app_ip_port.split(":")[1].split("/")[1:]) home_page_url = "" deployment_id = "" if pre_url: home_page_url = pre_url + "/" deployment_id = app_ip_port.split(":")[1].split("/")[3] print("Starting eureka register on eureka server " + self.host + ". \n") print(properties['name'] + " registering with: ip=" + app_ip + ", port=" + str(app_port) + ". \n") eureka_client.init(eureka_server=self.host, app_name=f"{properties['name']}{deployment_id}", instance_port=app_port, instance_ip=app_ip, health_check_url=f"{pre_url}/ping", home_page_url=f"{home_page_url}", status_page_url=f"{pre_url}/ping")
def main(): tornado.options.parse_command_line() # 注册eureka服务 eureka_client.init(eureka_server="http://localhost:9000/eureka/", app_name="python-service", instance_port=3333) app = tornado.web.Application( handlers=[(r"/test", IndexHandler), (r"/main", MainHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() try: res = eureka_client.do_service("RIBBON-PROVIDER", "/hello?name=python", return_type="string") print("result of other service" + res) except urllib.request.HTTPError as e: # If all nodes are down, a `HTTPError` will raise. print(e)
def create_app(): app = Flask(__name__) # CORS(app,resources=r'/*') app.secret_key = os.urandom(24) #生成一串随机24位的字符 bootstrap.init_app(app) if not os.path.exists('log'): os.mkdir('log') log = logger('flask') app.log = log """拦截器 对每个请求结束后做其他处理 """ @app.after_request def after_request(response): ip = request.remote_addr url = request.url app.log.info(str(response.status) + '-' + str(ip) + '-' + str(url)) return response eureka_client.init(eureka_server="http://10.132.166.121:5012/eureka", app_name="ig-web-mobile", instance_host='10.132.166.122', instance_port=8023, ha_strategy=eureka_client.HA_STRATEGY_RANDOM) from app.auth import auth as auth_bp app.register_blueprint(auth_bp, url_prefix='/auth') from app.security import security as security_bp app.register_blueprint(security_bp, url_prefix='/security') from app.hr import hr as hr_bp app.register_blueprint(hr_bp, url_prefix='/hr') from app.pageStream import stream as stream_bp app.register_blueprint(stream_bp, url_prefix='/stream') from app.decision import decision as decision_bp app.register_blueprint(decision_bp, url_prefix='/decision') return app
def create_app(config_filename=None): app = Flask(__name__, instance_relative_config=True) # read the environment parameter to retrieve the path to the configuration file if config_filename is None: app.config.from_envvar("LIBINTEL_SETTINGS") # check whether the query executor is part of a microservice architecture. # If it is, the configuration property 'EUREKA_URL' needs to be set. if app.config.get("EUREKA_URL") is not None: app.logger.info('registering with eureka server') server_url = app.config.get("EUREKA_URL") instance_port = int(os.environ.get("BIBLIOMETRICS_PORT", default=5000)) eureka_client.init(eureka_server=server_url, app_name="query-executor", instance_port=instance_port) app.elasticsearch = Elasticsearch([ app.config['ELASTICSEARCH_URL'] ]) if app.config['ELASTICSEARCH_URL'] else None app.logger.info('enabling CORS support') # enable CORS support CORS(app, origins='*') if app.config.get('LIBINTEL_ELASTICSEARCH_URL'): app.elasticsearch = Elasticsearch( app.config.get('LIBINTEL_ELASTICSEARCH_URL')) Bootstrap(app) # register all blueprints app.logger.info('registering blueprints') register_blueprints(app) base_location = app.config.get("LIBINTEL_DATA_DIR") create_folders(base_location) return app
def __init__(self, eureka_servers, resolver_name='eureka_nameresolver', start_listener=True, listen_timeout=30, connect_timeout=30): self._listening = False self._stopped = False self._listen_thread = None self._listen_timeout = listen_timeout self._lock = threading.Lock() instance_id = f'{resolver_name}:{self.get_ip()}' self._client = eureka_client.init(eureka_server=eureka_servers, app_name=resolver_name, instance_id=instance_id) self._names = {} if start_listener: self.start_listener() self._listen_timeout = listen_timeout
import flask from flask import request import json import py_eureka_client.eureka_client as eureka_client from ml import get_stocks_for_article eureka_client.init(eureka_server="http://*****:*****@app.route("/", methods=["GET"]) def get_recommendations(): try: auth = request.headers["Authorization"] if auth == None or not auth.startswith("Bearer"): return "Bearer token required for recommendations service" stocks_owned = _get_stocks_owned(request.headers) articles = _get_articles(request.headers) zipped_article_relevant_stocks = [ (article, set(get_stocks_for_article(article))) for article in articles ] recommendations = [ pair[0] for pair in zipped_article_relevant_stocks
import py_eureka_client.eureka_client as eureka import django.core.management.commands.runserver as runserver import socket import sys server_port = int(sys.argv[-1]) registry_client = eureka.init(eureka_server="http://127.0.0.1:8761", app_name="diabetes-app", instance_ip='127.0.0.1', instance_port=server_port)
from database import engine, models from api.v1 import api_router as v1_router from api.health import api_router as health_router from database.data.seed_data import seed_data models.Base.metadata.create_all(bind=engine) seed_data() app = FastAPI(title="Address service", openapi_url="/address/api/v1/openapi.json") app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(health_router) app.include_router(v1_router, prefix='/api/v1') eureka_client.init(eureka_server=settings.EUREKA_SERVER, app_name="address-service", instance_port=int(settings.APP_PORT), instance_ip=settings.APP_HOST) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=settings.APP_PORT)
def register_client(): eureka_client.init(eureka_server=HTTP + DISCOVERY_SERVICE_IP + COLON + DISCOVERY_SERVICE_PORT + "/eureka/", app_name=APPLICATION_NAME, instance_ip=INSTANCE_IP, instance_port=int(PORT))
def client_init(self, eureka_server, app_name, instance_port): eureka_client.init(eureka_server=eureka_server, app_name=app_name, instance_port=instance_port)
def register_eureka_service(app_name, instance_port, eureka_server=CommonConfig.EUREKA_SERVICE): eureka_client.init(eureka_server=eureka_server, instance_port=instance_port, app_name=app_name)