我敢肯定,如果您使用了jsonrpc4j(在spring容器之外),那么您将识别以下标准模式。

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       jsonRpcServer = new JsonRpcServer(myService, MyService.class);
       jsonRpcServer.set...
   }


我正在尝试创建一个包含所有JSON请求和JSON响应的日志文件。也就是说,我想在反序列化之前记录传入的JSON RPC请求,并在序列化之后记录传出的请求。

我一直在阅读代码,似乎没有一种简便的方法可以做到这一点。有人可以帮忙吗?

我提出的解决方案(有效)使用了多种修饰,但我对此不满意:

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       ObjectMapper mapper = new MyObjectMapper(null, null, null);
       jsonRpcServer = new MyJsonRpcServer(mapper, myService, null);
       jsonRpcServer.set...
   }
}


使用以下2个重载类:

class MyObjectMapper extends ObjectMapper {
    private static final Logger L = LoggerFactory.getLogger(MyObjectMapper.class);

    public MyObjectMapper(JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc) {
        super(jf, sp, dc);
    }

    @Override
    public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException,
JsonMappingException {
        super.writeValue(out, value);
        L.info("Out: " + writeValueAsString(value));
    }

}




class MyJsonRpcServer extends JsonRpcServer {
    private static final Logger L = LoggerFactory.getLogger(MyJsonRpcServer.class);

    public MyJsonRpcServer(ObjectMapper mapper, Object handler, Class<?> remoteInterface) {
        super(mapper, handler, remoteInterface);
    }

    @Override
    public void handleNode(JsonNode node, OutputStream ops) throws IOException {
        L.info("In: " + (node == null ? "(null)" : node.toString()));
        super.handleNode(node, ops);
    }
}


我认为这看起来和感觉有点讨厌。有更好的方法吗?

最佳答案

该库支持使用InvocationListenerhttps://github.com/briandilley/jsonrpc4j/blob/master/src/main/java/com/googlecode/jsonrpc4j/InvocationListener.java

您可以通过servlets init()方法将其添加到服务器,所有调用都将通过该方法。

这是二传手:https://github.com/briandilley/jsonrpc4j/blob/cfdaea92fedf7b43be9d93420df168fe69a5a4fa/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L994

因此,只需致电server.setInvocationListener,您就可以开始了。

09-10 02:26