最近有业务需求,在写消息推方面(APP,SMS)的实现代码,由于一些特殊原因(网络),需要实现一个消息重发的机制(如果发送失败的话,则重新发送,最多发送N次)
由于以上的一个需求,在实现的过程中,最开始想到的是使用监听(类似观察者模式的感觉),发送失败的话,即有相应的处理逻辑,但是由于一些原因,并没有使用这个方法,使用了以下书写的代理和注解机制,实现了重发效果,具体消息发送的代码使用dosomething代替;
如果您还有其他更好的方法,欢迎指导。
以下贴出来我的一些实现代码:
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’中