Registration and discovery services SpringCloud01--
A micro-service registration and discovery
We micro-services, often there are service providers, service consumers and service registration centers. Before we learn Zookeeper is a registered center. But in the official SpringCloud, it is not recommended to use ZK as a registration center, we tend to use eureka
Service providers, service consumers, the registry was a triangle
1. Service providers will be registered to the service center
2. Service consumers through the registry to find services
3. Find a service call
4. service consumers and service registration centers to maintain a heartbeat connection, once the address of the service provider is changed, the registry will notify the customer service
Second, the registry eureka
SpringCloud offers a variety of registry support, eureka, zk, etc., officially recommended eureka
科普:什么是Eureka?
Eureka是Netfix开源的服务发现组件,本身是一个基于Rest的服务。包含Server和Client两部分。SpringCloud将其集成在子项目Spring Cloud Netflix中,从而实现微服务的注册和发现。
2.1. Writing Eureka Server
2.1.1 Create a new Spring Starter, introduced eureka server
2.1.2. Creating a application.yml, start class @EnableEurekaServer
server:
port: 1111 #服务端口
eureka:
client:
register-with-eureka: false #是否将自己注册到Eureka服务中,自己本来就是服务无需注册
fetch-registry: false #是否从Eureka中获取注册信息
service-url: # Eureka客户端与Eureka服务端交互地址
defaultZone: http://localhost:${server.port}/eureka/
2.1.3. Create a new Spring Starter, import eureka, write a service
2.1.4. Creating a application.yml, start class @EnableDiscoveryClient, go to the registration center to register the above discovery
server:
port: 8081
spring:
application:
name: microservice-item
eureka:
client:
register-with-eureka: true
fetch-registry: true #是否从eureka中获取注册信息,默认true
service-url:
defaultZone: http://localhost:1111/eureka/
2.1.5. Writing Services (key codes)
@Service
public class ItemService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
/**
* 商品微服务进行查询
* @param id
* @return
*/
public Item queryItemById(Long id) {
List<ServiceInstance> instances = discoveryClient.getInstances("MICROSERVICE-ITEM");
ServiceInstance serviceInstance = instances.get(0);
String url="http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/item/"+id;
return restTemplate.getForObject(url, Item.class);
}
}
2.2 write. Eruka-client
2.2.1. Create a eruka-client, and discovery component added eruka web package
2.2.2. Writing the configuration file application.yml
#服务端口
server:
port: 8888
#应用名称及验证账号
spring:
application:
name: server-text
#注册中心
eureka:
# server:
# enable-self-preservation: false #关闭保护机制
# eviction-interval-timer-in-ms: 2000 #剔除失效服务间隔,单位毫秒
client:
register-with-eureka: true
fetch-registry: true
#设置服务注册中心的URL
service-url:
defaultZone: http://root:root@eureka-7901:7901/eureka/
instance:
hostname: server-text
2.2.3. Adding startup class notes
@EnableEurekaClient
2.2.4. After starting the cluster starts normally found