023-Spring Boot 服务的注册和发现
一、概述
服务调用
1.1、nginx方式
1.2、注册中心
二、注册中心【zookeeper】
2.1、安装zookeeper3.4.11
2.2、服务提供方,需要在服务启动时吗、,把服务的信息(IP,port)注册到注册中心。
在上一节的mall-product中pom
<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-x-discovery-server</artifactId> <version>2.12.0</version> </dependency>
增加配置
zookeeper.address=127.0.0.1:2181
增加注册类 ServiceRegister
@Component public class ServiceRegister implements ApplicationRunner { @Value("${zookeeper.address}") private String zkAddress; @Override public void run(ApplicationArguments args) throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(zkAddress, new RetryOneTime(1000)); client.start(); client.blockUntilConnected(); ServiceInstance<Object> instance = ServiceInstance.builder().name("product").address("127.0.0.1").port(8080).build();//注册了地址和端口 ServiceDiscovery<Object> discovery = ServiceDiscoveryBuilder.builder(Object.class).client(client) .basePath("/soa").build(); discovery.registerService(instance); discovery.start(); } }
可以再zookeeper客户端查看
ls / ls /soa ls /soa/product get /soa/product/d5770a1f-640f-4b17-b5d0-bfb2fd4b0623
查看注册服务具体信息
{"name":"product","id":"d5770a1f-640f-4b17-b5d0-bfb2fd4b0623","address":"127.0.0.1","port":8080,"sslPort":null,"payload":null,"registrationTimeUTC":1523196340298,"serviceType":"DYNAMIC","uriSpec":null,"enabled":true} cZxid = 0x10 ctime = Sun Apr 08 22:05:40 CST 2018 mZxid = 0x10 mtime = Sun Apr 08 22:05:40 CST 2018 pZxid = 0x10 cversion = 0 dataVersion = 0 aclVersion = 0 ephemeralOwner = 0x1007c571a950003 dataLength = 216 numChildren = 0
2.3、调用方
pom
<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-x-discovery</artifactId> <version>2.12.0</version> </dependency>
在进行调用额时候,需要先从注册中心获取到服务地址,然后根据获取到的服务地址进行调用。
调用
public static void main(String[] args) throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new RetryOneTime(1000)); client.start(); client.blockUntilConnected(); ServiceDiscovery<Object> discovery = ServiceDiscoveryBuilder.builder(Object.class).client(client) .basePath("/soa").build(); Collection<ServiceInstance<Object>> instances = discovery.queryForInstances("product"); instances.forEach((item) -> { System.out.println(item.getAddress()); System.out.println(item.getPort()); RestTemplate rt = new RestTemplate(); String string = rt.getForObject("http://" + item.getAddress() + ":" + item.getPort() + "/soa/product/1", String.class); System.out.println(string); Response<Product> fromJson = new Gson().fromJson(string, new TypeToken<Response<Product>>() { }.getType()); System.out.println(new Gson().toJson(fromJson)); }); }
如果有多个服务可以增加负载类即可
查看源码:https://github.com/bjlhx15/spring-boot.git
中的
其中mall-product中的
注册注册中心
其中mall-webz中的
client是测试代码,LoadBalance是负责均衡类