最近有业务需求,在写消息推方面(APP,SMS)的实现代码,因为一些特殊缘由(网络),须要实现一个消息重发的机制(若是发送失败的话,则从新发送,最多发送N次) java
因为以上的一个需求,在实现的过程当中,最开始想到的是使用监听(相似观察者模式的感受),发送失败的话,即有相应的处理逻辑,可是因为一些缘由,并无使用这个方法,使用了如下书写的代理和注解机制,实现了重发效果,具体消息发送的代码使用dosomething代替; 网络
若是您还有其余更好的方法,欢迎指导。 app
如下贴出来个人一些实现代码: ide
package test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 默认的重试次数 * @author alexgaoyh * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SMSRetry { int times() default 1; }
package test; /** * 发送接口 * @author alexgaoyh * */ public interface SMSToSend { @SMSRetry(times = 5) void doSomething(String thing); }
package test; /** * 发送服务 * @author alexgaoyh * */ public class SMSService implements SMSToSend { @Override public void doSomething(String thing) { System.out.println(thing); //若是下面的代码行并无被注释,说明在发送过程当中抛出了异常,那么接下来,会持续发送SMSToSend接口中定义的5次消息 //throw new RuntimeException(); } }
package test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 代理模式 * @author alexgaoyh * */ public class SMSRetryProxy implements InvocationHandler { private Object object; @SuppressWarnings("unchecked") public <T> T getInstance(T t) { object = t; return (T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t .getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { int times = method.getAnnotation(SMSRetry.class).times(); Object result = null; while (times-- > 0) { try { result = method.invoke(object, args); break; } catch (Exception e) { System.out.println(e.getStackTrace()); System.out.println("error happend, retry"); } } return result; } }
package test; /** * 短信业务为SMS "short message service" * 客户端测试方法 * @author alexgaoyh * */ public class SMSClient { public static void main(String[] args) { SMSToSend toDo = new SMSRetryProxy().getInstance(new SMSService()); toDo.doSomething("== (short message service)send short messages =="); } }
以上代码很简单,不过多进行解释; 测试
重发次数定义在‘发送接口中’5次,具体的发送代码在‘SMSService’中 this