服務(wù)發(fā)現(xiàn)框架 - Eureka
Eureka是Netflix開發(fā)的服務(wù)發(fā)現(xiàn)框架杂拨,本身是一個(gè)基于REST的服務(wù),主要用于定位運(yùn)行在AWS域中的中間層服務(wù)阎肝,以達(dá)到負(fù)載均衡和中間層服務(wù)故障轉(zhuǎn)移的目的改鲫。SpringCloud將它集成在其子項(xiàng)目spring-cloud-netflix中,以實(shí)現(xiàn)SpringCloud的服務(wù)發(fā)現(xiàn)功能栗菜。
Eureka包含兩個(gè)組件:Eureka Server和Eureka Client欠雌。
Eureka Server提供服務(wù)注冊(cè)服務(wù),各個(gè)節(jié)點(diǎn)啟動(dòng)后凛捏,會(huì)在Eureka Server中進(jìn)行注冊(cè)螃成,這樣EurekaServer中的服務(wù)注冊(cè)表中將會(huì)存儲(chǔ)所有可用服務(wù)節(jié)點(diǎn)的信息摄狱,服務(wù)節(jié)點(diǎn)的信息可以在界面中直觀的看到。
Eureka Client是一個(gè)java客戶端霍比,用于簡(jiǎn)化與Eureka Server的交互,客戶端同時(shí)也就是一個(gè)內(nèi)置的暴备、使用輪詢(round-robin)負(fù)載算法的負(fù)載均衡器桂塞。
在應(yīng)用啟動(dòng)后,將會(huì)向Eureka Server發(fā)送心跳,默認(rèn)周期為30秒馍驯,如果Eureka Server在多個(gè)心跳周期內(nèi)沒有接收到某個(gè)節(jié)點(diǎn)的心跳阁危,Eureka Server將會(huì)從服務(wù)注冊(cè)表中把這個(gè)服務(wù)節(jié)點(diǎn)移除(默認(rèn)90秒)玛痊。
Eureka Server之間通過(guò)復(fù)制的方式完成數(shù)據(jù)的同步,Eureka還提供了客戶端緩存機(jī)制狂打,即使所有的Eureka Server都掛掉擂煞,客戶端依然可以利用緩存中的信息消費(fèi)其他服務(wù)的API。綜上趴乡,Eureka通過(guò)心跳檢查对省、客戶端緩存等機(jī)制,確保了系統(tǒng)的高可用性晾捏、靈活性和可伸縮性蒿涎。
服務(wù)注冊(cè)服務(wù)- Eureka Server
1 、創(chuàng)建springboot項(xiàng)目 選擇組件 eurka-server
2惦辛、在EurekaServerApplication類中使用 @EnableEurekaServer 來(lái)說(shuō)明項(xiàng)目是一個(gè) Eureka
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3劳秋、修改配置文件,可以是 application.properties
server.port=8001
spring.application.name=eurka-server
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
默認(rèn) eureka server 也是一個(gè) eureka client胖齐,registerWithEureka: false 和 fetchRegistry: false 來(lái)表明項(xiàng)目是一個(gè) Eureka Server玻淑。
4.運(yùn)行 EurekaServerApplication類,啟動(dòng)項(xiàng)目呀伙,訪問(wèn)項(xiàng)目 [http://localhost]
(https://links.jianshu.com/go?to=http%3A%2F%2Flocalhost%2F):8001/补履,目前還沒有服務(wù)
2、服務(wù)提供者provider-one
1剿另、ProviderOneApplication啟動(dòng)類增加三個(gè)注解
選擇組件 Eureka client組件
@EnableEurekaClient :說(shuō)明這是一個(gè)Eureka服務(wù)
@SpringBootApplication:表明他是一個(gè)springboot項(xiàng)目
@MapperScan("com.spring.providerone.dao"):指定要變成實(shí)現(xiàn)類的接口所在的包箫锤,然后包下面的所有接口在編譯之后都會(huì)生成相應(yīng)的實(shí)現(xiàn)類
@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.spring.providerone.dao")
public class ProviderOneApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderOneApplication.class, args);
}
}
2、新建控制層:UserController .java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserServiceservice;
@RequestMapping("/userList")
public List getUserList(){
return service.findAllUser();
}
@RequestMapping("/add")
public String addUser(@RequestBody User user){
if(user!=null){
service.createUser(user);
return "success";
}else{
return "error";
}
}
@RequestMapping("/delUser")
public String delUser(@RequestParam String id){
try {
service.delUser(id);
return "del success";
}catch (Exception e ){
e.printStackTrace();
return "del false";
}
}
@RequestMapping("/updateUser")
public String updateUser(@RequestBody User user){
try {
service.updateUser(user);
return "update success";
}catch (Exception e ){
e.printStackTrace();
return "update false";
}
}
//測(cè)試方法雨女,返回服務(wù)器端口麻汰,以判斷是訪問(wèn)哪個(gè)服務(wù)
@Value("${server.port}")
Stringport;
@RequestMapping("/hi")
public String home(@RequestParam(value ="name", defaultValue ="zhangsan") String name) {
return "hi " + name +" ,i am from port:" +port;
}
}
3、配置文件修改:application.properties
注:serverTimezone=UTC戚篙,MySQL jdbc 6.0 版本以上須配置此參數(shù)五鲫,用戶名和密碼改為你本地的用戶名和密碼服務(wù)之間的調(diào)用都是根據(jù)spring.application.name=provider-user中的值:provider-user
spring.datasource.url=jdbc:mysql://localhost:3306/garbage?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=lch
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.typeAliasesPackage=com.spring.*.*.entity
mybatis.mapperLocations=classpath:mapper/*.xml
server.port=8002
spring.application.name=provider-user
eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
3、服務(wù)提供者provider-two
新建一個(gè)新的服務(wù)岔擂,相當(dāng)于一個(gè)小集群位喂,工程跟provider-one差不多,新建provider-two工程乱灵,其他文件可復(fù)制過(guò)來(lái)塑崖,注意UserDaoMapper.xml文件中引用的包名也需要改過(guò)來(lái),然后修改application.properties:
最后啟動(dòng)provider- two服務(wù)
這是去eureka服務(wù)注冊(cè)中心查看痛倚,就有兩個(gè)服務(wù)被注冊(cè)了
4规婆、服務(wù)消費(fèi)者 - Ribbon | Feign
Spring Cloud 兩種調(diào)用服務(wù)的方式,ribbon + restTemplate,和 feign抒蚜。
1掘鄙、新建工程,命名為:consumer-ribbon嗡髓,選擇組件Spring Web操漠,Spring Cloud Discovery中的Eureka Client、Routing中Ribbon和Spring Cloud Circuit Breaker 中的Hystrix
2饿这、application.properties配置
server.port=8004
spring.application.name=consumer-ribbon
eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
3浊伙、啟動(dòng)類新增@EnableEurekaClient注解,加 @EnableHystrix 注解開啟Hystrix长捧,向 Spring 注入一個(gè) bean: restTemplate嚣鄙,并添加 @LoadBalanced 注解,表明這個(gè) restTemplate 開啟負(fù)載均衡功能
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class ConsumerRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerRibbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
串结、新建服務(wù)層service:UserService
PROVIDER-USER為注冊(cè)服務(wù)里的名稱哑子,用來(lái)代替具體的URL,來(lái)調(diào)用/user/hi接口奉芦,
RestTemplate詳解赵抢,有興趣可以看看
@Service
public class UserService {
@Autowired
RestTemplaterestTemplate;
public String hiService(String name) {
return restTemplate.postForObject("http://PROVIDER-USER/user/hi?name="+name,null,String.class);
}
@HystrixCommand(fallbackMethod ="userListError")
public List userList() {
return restTemplate.postForObject("http://PROVIDER-USER/user/userList","",List.class);
}
@HystrixCommand(fallbackMethod ="addUserError")
public String addUser(User user) {
return restTemplate.postForEntity("http://PROVIDER-USER/user/add",user,String.class).getBody();
}
@HystrixCommand(fallbackMethod ="updateUserError")
public String updateUser(User user){
return restTemplate.postForEntity("http://PROVIDER-USER/user/updateUser",user,String.class).getBody();
}
@HystrixCommand(fallbackMethod ="delUserError")
public String delUser(String id){
return restTemplate.postForObject("http://PROVIDER-USER/user/delUser?id="+id,null,String.class);
}
public String hiError(String name) {
return "服務(wù)器開了小差剧蹂,請(qǐng)休息一會(huì)再試声功!";
}
public List userListError() {
return null;
}
public String addUserError(User user){return "服務(wù)器開了小差,請(qǐng)休息一會(huì)再試宠叼!";}
public String updateUserError(User user){return "服務(wù)器開了小差先巴,請(qǐng)休息一會(huì)再試!";}
public String delUserError(String id){return "服務(wù)器開了小差冒冬,請(qǐng)休息一會(huì)再試伸蚯!";}
}
5、新建控制層controller:UserControler
@RestController
public class UserControler {
@Autowired
UserServiceuserService;
@RequestMapping(value ="/hi")
public String hi(@RequestParam String name){
return userService.hiService(name);
}
@RequestMapping(value ="/userList")
public List userList(){
return userService.userList();
}
@RequestMapping(value ="/addUser")
public String addUser(@RequestParam String id,String username){
User user =new User();
user.setId(id);
user.setUsername(username);
return userService.addUser(user);
}
@GetMapping(value ="/updateUser")
public String updateUser(@RequestParam String id,String username){
User user =new User();
user.setId(id);
user.setUsername(username);
return userService.updateUser(user);
}
@GetMapping(value ="/delUser")
public String delUser(@RequestParam String id){return userService.delUser(id);}
}
}
6简烤、啟動(dòng)consumer-ribbon工程
多次請(qǐng)求hi接口:http://localhost:8004/hi?name=test剂邮,下面信息會(huì)交替出現(xiàn),說(shuō)明負(fù)載均衡已經(jīng)起作用了:
hi test ,i am from port:8002
hi test ,i am from port:8003
訪問(wèn):http://localhost:8004/addUser?id=2&username=lisi横侦,新增一條數(shù)據(jù)
[{"id":"3","username":"張三"},{"id":"2","username":"lisi"}]
訪問(wèn):http://localhost:8004/updateUser?id=2&username=李四挥萌,修改數(shù)據(jù)
update success
訪問(wèn):http://localhost:8004/delUser?id=2,刪除數(shù)據(jù)
del success
4.2枉侧、Feign+Hystrix
1引瀑、新建一個(gè)Spring Boot工程,命名為:consumer-feign榨馁,選擇組件spring could routing 打勾OpenFeign
2憨栽、application.properties配置。Feign 自帶斷路器,它沒有默認(rèn)打開屑柔,需要在配置文件中配置打開屡萤,feign.hystrix.enabled=true
server.port=8005
spring.application.name=consumer-feign
eureka.client.service-url.defaultZone=http://localhost:8001/eureka/
feign.hystrix.enabled=true
3、啟動(dòng)類ConsumerFeignApplication上添加 @EnableEurekaClient 和 @EnableFeignClients 注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignApplication.class, args);
}
}
4锯蛀、增加斷路實(shí)現(xiàn)類:HystricService.java
@Component
public class HystricServiceimplements UserService{
@Override
public String sayHiFromClientOne(String name) {
return "服務(wù)器開了小差灭衷,請(qǐng)休息一會(huì)再試!";
}
@Override
public List getUserList(){
return null;
}
@Override
public String addUser(User user){return "服務(wù)器開了小差旁涤,請(qǐng)休息一會(huì)再試翔曲!";}
@Override
public String updateUser(User user){return "服務(wù)器開了小差,請(qǐng)休息一會(huì)再試劈愚!";}
@Override
public String delUser(String id){return "服務(wù)器開了小差瞳遍,請(qǐng)休息一會(huì)再試!";}
}
5菌羽、新增service服務(wù):UserService.java
通過(guò)@ FeignClient(“服務(wù)名”)掠械,來(lái)指定調(diào)用哪個(gè)服務(wù),@GetMapping("接口名")注祖,來(lái)向接口發(fā)送 Get 請(qǐng)求猾蒂,@RequestParam 是請(qǐng)求參數(shù)
fallback指向熔斷實(shí)現(xiàn)類HystricService.java,當(dāng)服務(wù)不可用時(shí)會(huì)執(zhí)行熔斷實(shí)現(xiàn)類
@FeignClient(value ="provider-user",fallback = HystricService.class)
public interface UserService {
@GetMapping("/user/hi")
String sayHiFromClientOne(@RequestParam(value ="name") String name);
@GetMapping("/user/userList")
List getUserList();
@GetMapping("/user/add")
String addUser(User user);
@GetMapping("/user/updateUser")
String updateUser(User user);
@GetMapping("/user/delUser")
String delUser(@RequestParam String id);
}
6是晨、增加controller類:UserController.java
@RestController
public class UserController {
@Autowired
UserServiceuserService;
@GetMapping(value ="/hi")
public String sayHi(@RequestParam String name) {
return userService.sayHiFromClientOne( name );
}
@GetMapping(value ="/userList")
public List userList() {
return userService.getUserList();
}
@GetMapping(value ="/addUser")
public String addUser(@RequestParam String id,String username){
User user =new User();
user.setId(id);
user.setUsername(username);
return userService.addUser(user);
}
@GetMapping(value ="/updateUser")
public String updateUser(@RequestParam String id,String username){
User user =new User();
user.setId(id);
user.setUsername(username);
return userService.updateUser(user);
}
@GetMapping(value ="/delUser")
public String delUser(@RequestParam String id){return userService.delUser(id);}
}
8肚菠、啟動(dòng)consumer-feign項(xiàng)目,訪問(wèn)http://localhost:8005/hi?name=test,以下信息交替出現(xiàn)罩缴,說(shuō)明已經(jīng)啟動(dòng)負(fù)載均衡了
hi test ,i am from port:8002
hi test ,i am from port:8003
訪問(wèn):http://localhost:8005/addUser?id=2&username=lisi 蚊逢,新增一條數(shù)據(jù)
success
再次訪問(wèn):http://localhost:8005/userList, 出現(xiàn)以下信息說(shuō)明新增成功箫章!
[{"id":"3","username":"張三"},{"id":"2","username":"lisi"}]
訪問(wèn):http://localhost:8005/updateUser?id=2&username=李四烙荷,修改數(shù)據(jù)
update success
訪問(wèn):http://localhost:8005/delUser?id=2,刪除數(shù)據(jù)
del success
9檬寂、把兩個(gè)服務(wù)停止终抽,再去訪問(wèn)http://localhost:8005/hi?name=test,顯示以下信息說(shuō)明斷路器已經(jīng)生效了
服務(wù)器開了小差桶至,請(qǐng)休息一會(huì)再試昼伴!
作者:betake
鏈接:http://www.reibang.com/p/63665a2f2414
來(lái)源:簡(jiǎn)書。