package com.example.server1;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.web.client.RestTemplate;
import com.google.common.eventbus.Subscribe;
import com.model.User;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.infix.lang.infix.antlr.EventFilterParser.predicate_return;
import rx.schedulers.Schedulers;
import rx.Observable;
import rx.Observable.*;
import rx.Subscriber;
import rx.subscriptions.*;
public class UserObservableCommand extends HystrixObservableCommand<User> {
private RestTemplate restTemplate;
private Long id;
public UserObservableCommand(Long id) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.id = id;
System.out.println("执行构造方法");
}
@Override
protected rx.Observable<User> construct() {
System.out.println("执行 construct 方法");
return Observable.create(new Observable.OnSubscribe<User>() {
@Override
public void call(Subscriber<? super User> observer) {
try {
System.out.println("测试开始");
if (!observer.isUnsubscribed()) {
System.out.println("确认订阅");
//User user = restTemplate.getForObject("http://hello-service/users/{1}", User.class,id);
User user = new User();
user.setId(1L);
user.setName("lixia");
observer.onNext(user);
User user2 = new User();
user2.setId(2L);
user2.setName("caocao");
observer.onNext(user2);
observer.onCompleted();
}
} catch (Exception e) {
observer.onError(e);
}
}
});
}
public static void main(String[] args) {
UserObservableCommand userObservableCommand = new UserObservableCommand(1L);
Observable<User> user=userObservableCommand.construct();
/*在下面的 Lambda 表达式中自动设置参数 user2 设置为 USER类型,因为 subscribe 方法提取的是Observable<User>
* 的元素,所以参数 user2 的类型为 USER。
*
* */
user.subscribe(user2->{System.out.println("名字:" + user2.getName());
System.out.println("ID:" + user2.getId());});
}
}
执行输出如下:
16:30:40.473 [main] DEBUG com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty - Flipping property: hystrix.threadpool.ExampleGroup.metrics.rollingStats.timeInMilliseconds to use NEXT property: hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds = 10000
16:30:40.473 [main] DEBUG com.netflix.hystrix.strategy.properties.HystrixPropertiesChainedProperty - Flipping property: hystrix.threadpool.ExampleGroup.metrics.rollingStats.numBuckets to use NEXT property: hystrix.threadpool.default.metrics.rollingStats.numBuckets = 10
执行构造方法
执行 construct 方法
测试开始
确认订阅
名字:lixia
ID:1
名字:caocao
ID:2