
在微服务中,不同的业务被拆分成不同的服务,不同的服务之间会相互依赖,而管理这些服务就变得尤为重要
搭建服务注册中心
服务注册中心使用Spring Cloud的Eureka Server
java开发环境使用的idea
创建一个spring boot项目
取好名字
选择web模块 (如果直接选择Cloud Discovery下面Eureka Server也可以会自动加入相关依赖)
创建好项目之后在dependencies中加入maven的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
然后可能会出现maven找不到依赖的情况
估计是spring cloud没有找到对应的eureka的版本,加一个版本号就可以了(版本号可以到maven仓库中去看)
在启动类上加入注解@EnableEurekaServer
在application.properties中配置下项目
#项目名称 spring.application.name=service_center #项目启动端口 server.port=8666 #取消该使用启动eureke客户端 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false
然后运行访问8666端口就可以看到服务注册中心了
注册服务到注册中心
创建.net core 的webapi项目
订单服务OrderService
1:使用nuget命令安装相关依赖
install-package Pivotal.Discovery.Client -version 1.1.0
2:Startup.cs中加入相关依赖
public void ConfigureServices(IServiceCollection services) { services.AddDiscoveryClient(Configuration); // Add framework services. services.AddMvc(); }
use
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseDiscoveryClient(); app.UseMvc(); }
3:appsettings.json中加入eureka配置
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "spring": { "application": { "name": "OrderService" } }, "eureka": { "client": { "serviceUrl": "http://localhost:8666/eureka/", "shouldFetchRegistry": false, "shouldRegisterWithEureka": true }, "instance": { "port": 9000 } } }
然后运行项目就可以看到服务被注册到注册中心去了
这种在iis方式运行端口不是太好控制可以使用Kestrel的方式运行
在Program.cs 设置好地址
然后就运行的时候就可以直接在Program.cs 位置使用命令dotnet run启动项目
其他服务注册的方式一样,重复步骤即可
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价