Основанный на Netty, Forest представляет собой лёгкий и высокопроизводительный распределённый RPC-сервис. Он отличается простотой использования и эффективностью.
Используйте аннотацию @ServiceProvider
для предоставления сервиса и @MethodProvider
для настройки метода по умолчанию, включая параметры сжатия, сериализации и тайм-аута для клиента.
@ServiceProvider(serviceName = "sampleService", haStrategyType = HaStrategyType.FAIL_FAST,
loadBalanceType = LoadBalanceType.RANDOM, connectionTimeout = Constants.CONNECTION_TIMEOUT)
public interface SampleService {
@MethodProvider(methodName = "say")
String say(String str);
@MethodProvider(methodName = "echo", serializeType = SerializeType.Hession2, compressType = CompressType.None)
String echo(String msg);
}
Для публикации сервиса используйте аннотацию @ServiceExport
, а для публикации метода — @MethodExport
.
@Path("/sample")
@ServiceExport
public class SampleServiceImpl implements SampleService {
/**
* Поддержка Jersey, может быть включена через конфигурацию, одновременно запуская HTTP-сервер.
*
* @param str
* @return
*/
@Path("/hello/{str}")
@GET
@Produces("text/plain")
@MethodExport
@Rate(2)
@Override
public String say(@PathParam("str") String str) {
return "say " + str;
}
@Interceptor("metricInterceptor")
@MethodExport
@Override
public String echo(String msg) {
return "echo>>> " + msg;
}
}
application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans" xmlns:forest="http://api.zhizus.com/schema/forest"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://api.zhizus.com/schema/forest http://api.zhizus.com/schema/forest.xsd">
<context:component-scan base-package="com.zhizus.forest.demo"/>
<context:property-placeholder location="classpath:/*.properties"/>
<forest:registry id="registry" regProtocol="local" name="registry" address="127.0.0.1:2181"/>
<!--<forest:registry id="registry" regProtocol="zookeeper" name="registry" address="127.0.0.1:2181"/>-->
<forest:server id="forestServer" registry="registry" startHttpServer="true"/>
<forest:interceptors>
<forest:interceptor id="metricInterceptor" class="com.zhizus.forest.support.MetricInterceptor" auto-match="public *(*)"/>
</forest:interceptors>
</beans>
public class SampleServer {
public static void main(String[] args) throws Exception {
new ClassPathXmlApplicationContext(new String[]{"application.xml"});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:forest="http://api.zhizus.com/schema/forest"
xsi:schemaLocation="http://www.springframework.org/schema/beans
``` **Контекст: компонентное сканирование базового пакета com.zhizus.forest.demo.client**
<context:component-scan base-package="com.zhizus.forest.demo.client"/>
**Реестр леса: идентификатор реестра — «registry», протокол регистрации — «local», имя — «registry», адрес — 127.0.0.1:9999**
<forest:registry id="registry" regProtocol="local" name="registry" address="127.0.0.1:9999"/>
**Справочник леса: идентификатор sampleService, интерфейс com.zhizus.forest.demo.api.SampleService, реестр — registry**
<forest:referer id="sampleService" interface="com.zhizus.forest.demo.api.SampleService" registry="registry">
<forest:method name="echo" timeout="5000" serializeType="Fastjson"/>
<forest:method name="say" timeout="5000" serializeType="Fastjson" compressType="GZIP"/>
</forest:referer>
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"application-client.xml"}); SampleService bean = (SampleService) context.getBean("sampleService"); String test = bean.say("hello");
### Вывод в консоль
23:10:10.295 [pool-1-thread-1] INFO MetricInterceptor 34 - methodName:/sampleService/say, current tps:83342, avgTime:0, maxTime:63, minTime:0 23:10:11.298 [pool-1-thread-1] INFO MetricInterceptor 34 - methodName:/sampleService/say, current tps:86271, avgTime:0, maxTime:63, minTime:0 23:10:12.295 [pool-1-thread-1] INFO MetricInterceptor 34 - methodName:/sampleService/say, current tps:86063, avgTime:0, maxTime:63, minTime:0 23:10:13.295 [pool-1-thread-1] INFO MetricInterceptor 34 - methodName:/sampleService/say, current tps:84305, avgTime:0, maxTime:63, minTime:0
[Дополнительные примеры](https://github.com/dempeZheng/forestRPC/tree/master/forest-demo)
# Документы
* [Wiki (на китайском)](https://github.com/dempeZheng/forest/wiki/zh_quick_start)
# Задачи
- Поддержка межъязыковых протоколов
- Управление сервисами через административную панель
# Лицензия
Forest выпущен под [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )