在Spring Cloud Netflix栈中,各个微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端。我们可以使用JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client, Spring的RestTemplate。但是,用起来最方便、最优雅的还是要属Feign了。
Feign简介
Feign是一个声明式的Web服务客户端,使用Feign可使得Web服务客户端的写入更加方便。
它具有可插拔注释支持,包括Feign注解和JAX-RS注解、Feign还支持可插拔编码器和解码器、Spring Cloud增加了对Spring MVC注释的支持,并HttpMessageConverters在Spring Web中使用了默认使用的相同方式。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。
Spring Cloud Feign简介参考:https://www.jb51.net/article/133773.htm
根据专家学者提供的账号密码,要在用户表注册一个专家学者账号(用户和专家学者不同的数据库)
在userContorller.java写一个方法:注册专家学者账号
/**
* 专家学者注册
*
* @param username
* @param password
* @return
*/
@ApiOperation(value = "专家学者注册")
@RequestMapping(value = "/registExpert", method = RequestMethod.POST)
public long registExpert(@RequestParam("username") String username, @RequestParam("password") String password) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
userService.insertSelective(user);
long userId = user.getUserId();
return userId;
}
UserClient.java(这里的接口和要远程调用的controller方法声明一样(此处是UserController.java),可直接复制过来,如下所示)
package com.lgsc.cjbd.expert.remote.client;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.lgsc.cjbd.vo.Response;
@FeignClient(name = "cjbd-user", fallback = UserClientFallback.class)
public interface UserClient {
/**
* 注册专家学者
*/
@RequestMapping(value = "/user/user/registExpert", method = RequestMethod.POST)
long registExpert(@RequestParam("username") String username, @RequestParam("password") String password);
}
以及失败回调用UserClientFallBack.java
package com.lgsc.cjbd.expert.remote.client;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import com.lgsc.cjbd.vo.Response;
/**
* 失败回调
*
* @author yeqj
*/
@Component
public class UserClientFallback implements UserClient {
private static Logger log = LogManager.getLogger(UserClientFallback.class);
@Override
public long registExpert(String username, String password, String realName) {
log.error("远程调用失败,注册专家学者失败,参数:[username=" + username + ",password=" + password + "]");
return 0;
}
}
之后再专家学者Service层传递专家学者用户名和密码过去,在用户表新增专家学者注册记录
userClient.registExpert(username, password);
即可完成远程调用
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。