一 会员模块
1 添加会员查找服务
package org.crazyit.cloud;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MemberController {
@RequestMapping(value = "/member/{id}", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public Member call(@PathVariable Integer id) {
Member p = new Member();
p.setId(id);
p.setName("angus");
return p;
}
}
2 启动会员模块
二 销售模块
1 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2 添加控制类
package org.crazyit.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
private MemberService memberService;
@RequestMapping(value = "/router", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public Member router() {
return memberService.getMember(1);
}
}
3 新建服务类
package org.crazyit.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Service
//@DefaultProperties(defaultFallback = "getMemberFallback")
public class MemberService {
@Autowired
private RestTemplate restTpl;
@HystrixCommand(fallbackMethod = "getMemberFallback", groupKey = "MemberGroup", commandKey = "MemberCommandKey",
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
}, threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2")
})
public Member getMember(Integer id) {
try {
Thread.sleep(2000);
} catch (Exception e) {
}
Member member = restTpl.getForObject(
"http://spring-hy-member/member/{id}", Member.class, id);
return member;
}
public Member getMemberFallback(Integer id) {
Member m = new Member();
m.setId(1);
m.setName("error member");
return m;
}
}
4 启动项目并测试