Based on RPC implemented by the Rest service, RPC implemented by the Rest Service

Source: Internet
Author: User
Tags tojson

Based on RPC implemented by the Rest service, RPC implemented by the Rest Service

Now there are many mature RPC frameworks, similar to Motan and Dubbo, but today I provide a Rest-based Rpc. Http://www.cnblogs.com/LipeiNet/p/5856414.html connected to the previous article

1: Principle

First, we need to establish a Rest service. If other applications want to obtain the resources of this service, they only need a URI. However, because the calling of internal programs is inconvenient for us to obtain json through URI and then process it by ourselves, and it is not appropriate, we need to use an intermediate layer, repackage the resources returned for access to the Rest service, and other projects only need to call this rpc project. For example

2. Implement the Rest Service

2.1: Define an implementation object for returning to the consumer (as agreed by myself)

Public class ResponseBean implements Serializable {private static final long serialVersionUID =-1L; public static final int SUCCESS = 10; public static final int FAILURE = 20; public static final int LOCKED = 30; public static final int EXCEPTION = 40; private int returnCode; // The Code returned to the consumer (0 indicates that the call is successful, and 1 indicates that the call fails) private String returnMsg; // return the error message private int dataCount to the consumer; // return the int type private String returnData; // return the json private Object returnObject; // return the public ResponseBean () Object () {} public ResponseBean (int returnCode, String returnMsg) {this. returnCode = returnCode; this. returnMsg = returnMsg;} public Object getReturnObject () {return this. returnObject;} public void setReturnObject (Object returnObject) {this. returnObject = returnObject;} public int getDataCount () {return this. dataCount;} public void setDataCount (int dataCount) {this. dataCount = dataCount;} public String getReturnData () {return this. returnData;} public void setReturnData (String returnData) {this. returnData = returnData;} public int getReturnCode () {return this. returnCode;} public void setReturnCode (int returnCode) {this. returnCode = returnCode;} public String getReturnMsg () {return this. returnMsg;} public void setReturnMsg (String returnMsg) {this. returnMsg = returnMsg ;}}

2.2: Set an ApiService for external requests

public interface ApiService {     String getToken();     ResponseBean add(String reqJson);}
Public class ApiServiceImpl implements ApiService {private static final Log log = LogFactory. getLog (ApiServiceImpl. class); @ Autowired private UserDao userDao; private String token; // For calling rpc verification use public String getToken () {return token;} public ResponseBean add (String reqJson) {ResponseBean responseBean = new ResponseBean (ResponseBean. SUCCESS, "successful call"); try {Map map = JsonUtil. g. fromJson (reqJson, HashMap. class); String username = map. get ("username "). toString (); String password = map. get ("password "). toString (); String realname = map. get ("realname "). toString (); Long userroleid = Double. valueOf (map. get ("userroleid "). toString ()). longValue (); UserBean userBean = new UserBean (); userBean. setCreatedate (new Date (); userBean. setPassword (password); userBean. setUserroleid (userroleid); userBean. setRealname (realname); userBean. setUsername (username); int count = userDao. add (userBean); responseBean. setReturnData (JsonUtil. g. toJson (count); responseBean. setReturnCode (10);} catch (Exception e) {log. error (e. getStackTrace (); responseBean. setReturnCode (11); responseBean. setReturnMsg ("server exception");} return responseBean;} public void setToken (String token) {this. token = token; // used to set the token (used to verify whether the consumer's token is the server's token )}}

2.3: defines the http request entry. Three parameters are required: token (for Security Authentication), m (for request method name), and reqJson (for request parameters)

@ Controller @ RequestMapping (value = "/api") public class ApiController {private static final Log log = LogFactory. getLog (ApiController. class); @ Autowired private ApiService apiService; /*** call method publicly ** @ param m interface method * @ param reqJson request parameter * @ param token request token * @ return */@ RequestMapping (value =" /exec ", method = RequestMethod. POST) @ ResponseBody public Object exec (@ RequestParam (value = "m", r Equired = true) String m, @ RequestParam (value = "reqJson", required = true) String reqJson, @ RequestParam (value = "token", required = true) String token) {log.info (String. format ("m = % s, reqJson = % s, token = % s", m, reqJson, token); Class c = apiService. getClass (); Method method = null; ResponseBean responseBean = null; if (! Token. equals (apiService. getToken () {log. error ("token Verification Failed, token =" + token); responseBean = new ResponseBean (ResponseBean. FAILURE, "Verification Failed"); return responseBean;} try {method = c. getMethod (m, String. class); // use reflection to find the corresponding method} catch (Exception e) {log. error ("m parameter error, m =" + m + "; req =" + reqJson, e); responseBean = new ResponseBean (ResponseBean. FAILURE, "m parameter error m =" + m); return responseBean;} if (StringUtils. isEmpty (reqJson) {log. error ("Empty reqJson"); responseBean = new ResponseBean (ResponseBean. FAILURE, "EMPTY reqJson"); return responseBean;} try {Object json = method. invoke (apiService, reqJson); return json;} catch (Exception e) {log. error ("processing exception, m =" + m + "; req =" + reqJson, e); responseBean = new ResponseBean (ResponseBean. FAILURE, "server Exception Handling"); return responseBean ;}}}

Through the above, we have implemented a rest service for consumers to call.

3: RPC wraps the rest Service

3.1: Define the webService required by the consumer

public interface WebService {    ResponseBean add(UserBean userBean);}

Implement webService

Public class WebserviceImpl implements WebService {private final static Log log = LogFactory. getLog (WebserviceImpl. class); private String url; // url set by the consumer private String token; // url set by the consumer public void setUrl (String url) {this. url = url;} public void setToken (String token) {this. token = token;} @ Override public ResponseBean add (UserBean userBean) {Map <String, String> map = new HashMap (); Res PonseBean rb = null; map. put ("token", token); map. put ("reqJson", JsonUtil. g. toJson (userBean); String reqUrl = url + "? M = add "; // set the method log to be accessed. debug (reqUrl); try {String str = HttpClientUtil.exe cuteHttpRequestUTF (reqUrl, map); // access the resource to obtain the returned json log. debug ("add return data:" + str); rb = JsonUtil. g. fromJson (str, ResponseBean. class); // converts json to log. debug ("getPromInfo return Regions data" + reqUrl); return rb;} catch (Exception e) {rb = new ResponseBean (); rb. setReturnObject (e); log. debug (e. getStackTrace (); return rb ;}}}

Then Package and release the rpc, and other applications can use it directly.

4: Configuration

Add in applicationconfig

<Mvc: annotation-driven/>
<Mvc: default-servlet-handler/>
<Mvc: annotation-driven/> the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans are automatically registered. Otherwise, an exception occurs.

<Bean id = "ApiService" class = "com. lp. rpc. impl. ApiServiceImpl">
    <property name="token" value="41729ff3-3406-4fc5-aeca-04f98892999b"></property>
</bean>
Consumer Configuration:
<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="webService" class="com.lp.rpc.impl.WebserviceImpl">    <property name="url" value="http://192.168.0.101:8088/api/exec"></property>    <property name="token" value="41729ff3-3406-4fc5-aeca-04f98892999b"></property></bean></beans>
5. Start a project and call the rpc project.
Public class AppMain {public static void main (String [] args) {ApplicationContext context = new ClassPathXmlApplicationContext ("application-config.xml"); WebService webService = (WebService) context. getBean ("webService"); UserBean userBean = new UserBean (); userBean. setUsername ("lisi"); userBean. setPassword ("123456"); userBean. setRealname ("Li Si"); userBean. setUserroleid (2); userBean. setCreatedate (new Date (); ResponseBean result = webService. add (userBean); if (StringUtils. equals (result. getReturnData (). toString (), "1") {System. out. print ("added successfully ");}}}
6. Summary

You can call different projects at the above level.

Advantage: easy to use, easy to control, and efficient.

Disadvantage: low security and url maintenance are required. Sometimes, when other services are enabled repeatedly, the call may fail.

Source Code address

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.