在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简介参考: http://www.tuohang.net/article/167082.html
根据专家学者提供的账号密码,要在用户表注册一个专家学者账号(用户和专家学者不同的数据库)
在usercontorller.java写一个方法:注册专家学者账号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * 专家学者注册 * * @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),可直接复制过来,如下所示)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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层传递专家学者用户名和密码过去,在用户表新增专家学者注册记录
1 |
userclient.registexpert(username, password); |
即可完成远程调用
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://blog.csdn.net/pomay/article/details/73776300
查看更多关于使用Spring Cloud Feign远程调用的方法示例的详细内容...