自己搭建阿里的hsf

    HSF相比DUBBO更稳当和快速,但是阿里云的edas又是收费的。虽然HSF不开源,但是自己搭建起来还是可以跑的

    1.新建的maven项目里面加入以下依赖

    <dependency>
        <groupId>com.alibaba.hsf</groupId>
        <artifactId>LightApi</artifactId>
        <version>1.0.0</version>
        </dependency>

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>hsf.schema</artifactId>
            <version>edas1.0.0</version>
        </dependency>

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

hsf是和spring集成的,所以要加入spring的依赖。

LightApi 里面有轻量级测试HSF的API

hsf.schema 里面包含 hsf的xml定义

    2.新建一个接口io.example.hsf.ICalService

  新建类实io.example.hsf.CalServiceImp现这个接口。用@Service("calService")标注这个类,因为之后会使用spring的扫描得把这个bean注册到spring。

    3.在classpath下面新建一个applicationContext文件。加入 <context:component-scan base-package="io.example.hsf"/> 目的就是扫描service,并且加入

<hsf:provider id="calService"
        interface="io.example.hsf.ICalService" ref="calService"
        version="1.0.0" group="testHSFGroup">
    </hsf:provider>

hsf:provider 就是把这个服务用对应的接口名、版本、分组暴露出去。

    4.启动项目,首先要启动edas-config-center,并且在hosts文件加入127.0.0.1 jmenv.tbsite.net,使HSF服务注册在本地,在JVM参数里面要加上潘多拉临时文件的位置-Dcom.taobao.pandora.tmp_path=/tmp/phsf0,在alitomcat要加入潘多拉的位置,也就是taobao-hsf.sar的位置。启动成功了会出现

    5.测试服务。既然HSF服务以及有了,我们可以不必使用alitomcat测试HSF服务。main方法也可以。

    

public static void main(String[] args) throws Exception {
	
		/**
		 * 设置潘多拉路径
		 */
		ServiceFactory.addJVMProperty("com.taobao.pandora.tmp_path", "E:/tmp/p201");
		
		ServiceFactory factory=ServiceFactory.getInstanceWithPath("F:/ali/");
		ConsumerService consumerService=factory.consumer("testconsumer").
		service("io.example.hsf.ICalService").
		version("1.0.0").group("testHSFGroup");
		
		
		consumerService.subscribe();
		consumerService.sync();
		System.out.println(consumerService.addresses());
		ICalService itemService= (ICalService)consumerService.subscribe();
		System.out.println( itemService.addNum(1, 2));
		
		
		
		
	}

    使用main方法也一样要指定潘多拉相关的参数。

之后使用consumer.version()设置版本group设置分组service设置接口名。

调用consumer.subscribe 就会尝试获取这个服务并且获得代理对象。多次调用并不会影响性能,第二次之后的调用会直接拿consumer的代理对象。

猜你喜欢

转载自my.oschina.net/u/778875/blog/983608
hsf
今日推荐