1. 什么是服务?
在软件开发领域,到处可见服务一词,而我们这里说的服务,我个人觉得与“微服务”这个词是分不开。微服务架构近两年兴起,Spring Cloud正是微服务架构的一套解决方案或者框架。
那什么是微服务呢?
官方定义如下:
The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services , which may be written in different programming languages and use different data storage technologies.
– James Lewis and Martin Fowler
想更多了解,可以阅读Martin Fowler的《Microservices》.
简单的说,微服务架构就是将一个完整的应用从数据存储开始垂直拆分成多个不同的服务,每个服务都能独立部署、独立维护、独立扩展,服务与服务间通过诸如RESTful API或者RPC等方式互相调用。
2. Service Registry(服务注册与发现)
在了解什么是服务之后,下面我们来看看要如何使用Spring Cloud去实现服务的注册和发现。
要实现服务的注册的发现,Spring Cloud提供的不止一套方案,其中Spring Cloud Zookeeper, Spring Cloud Consul 和 Spring Cloud Eureka都可以实现,而这里我们要用Eureka去实现。
接下来,让我们动手写一些代码做一下尝试:
2.1 Service Registry ( 服务注册中心 )
怎么去实现一个服务注册中心,只需要使用spring-cloud-starter-eureka-server
便可轻松完成。
首先,创建一个基础的Spring Boot工程,并在pom.xml
中引入需要的依赖内容:
1 | <parent> |
然后,使用@EnableEurekaServer
注解来启动一个服务注册中心:
1 |
|
在默认配置下,服务注册中心有个自注册的行为,也就是说它会默认把自己当成客户端注册给自己,而在单实例运行情况下,我们不需要这样的自注册行为,所以我们可以通过配置关闭这种行为:
1 | server: |
服务注册中心是自带UI界面的,默认情况下,使用8761端口。如上所示,我们同样可以更改配置文件来修改服务器端口,例如:1234,1111,等等。
这样,我们就可以启动我们的应用,启动完成后,我们可以访问:http://localhost:8761
可以看到下面的页面,不过现在还没有任何服务注册进来:
示例代码: Github : eureka-server