我们这是一个微服务架构的项目实战,那么在微服务架构的项目中必然是少不了服务注册中心的。这种关系类似于当前做Java开发的必然是少不了Spring一样,巧的是,服务注册中心的作用也有点类似Spring中的Bean管理。只是服务注册中心管理的是一个个的微服务,其实技术这个东西学到一定程度之后,归纳起来好像都大同小异。
实现服务注册的方式也有很多种,比如Dubbo
、Zookeeper
、Eureka
、Consul
以及Nacos
,本项目使用Eureka
进行服务的注册与发现,其它框架后面有时间的话也会进行学习和总结。好了,废话不多说,正式开始吧。
1. 代码开发
注册中心既然是用来管理一个个的微服务,那微服务是需要被管理的对象,我们通常称为客户端。对应的注册中心就会有服务端,今天我们也是主要搭建注册中心的服务端,并且我们暂时不考虑注册中心集群。
注册中心服务端的工程名:mall-registry-server
。
1.1 引入依赖
使用Eureka
实现服务注册中心的服务端,主要引入以下两个依赖:
<dependencies>
<!--Eureka Server必须引入的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--引入Spring Security,实现安全认证-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
1.2 添加配置文件
一个单机版的服务注册中心配置很简单,主要是定义spring.application.name
、server.port
以及eureka.*
的一些配置,因为我们引入了Spring Security
,所以我们还需要配置spring.security
设置一个默认用户和密码。
spring:
application:
name: mall-registry-server
security:
user:
name: Anbang713
password: pwd713
server:
port: 9010
eureka:
instance:
hostname: localhost # 如果需要部署集群,则必须使用域名
prefer-ip-address: true
instance-id: ${spring.application.name}:${server.port}
client:
registerWithEureka: false #如果是集群部署,则注册中心服务端需要相互注册
fetchRegistry: false
service-url:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
server:
eviction-interval-timer-in-ms: 5000 # 每隔5秒钟,进行一次服务列表的清理
1.3 添加启动类
在启动类上增加@EnableEurekaServer
注解即可。
@SpringBootApplication
@EnableEurekaServer
public class RegistryServerApplication {
public static void main(String[] args) {
SpringApplication.run(RegistryServerApplication.class, args);
}
}
1.4 添加安全认证配置类
我们的服务注册地址是:http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:${server.port}/eureka/
,因为引入Spring Security
依赖来保护注册中心的控制台访问权限,但同时服务注册地址也会被保护起来,服务注册的客户端想要注册到注册中心的客户端,就需要授权。显然这是没有必要的,所以我们需要关闭htpp://xxx/eureka/*
这个地址的保护。因此引入安全认证配置类:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().ignoringAntMatchers("/eureka/**");
super.configure(http);
}
}
2. 服务启动
执行启动类RegistryServerApplication
,然后通过浏览器访问http://localhost:9010
,会跳转到登录页:
输入在application.yml
中配置的用户名和密码,登录成功后进入到Eureka
服务监控台: