一些抽象的代码写法

需求:根据不同的发送消息类型,去写不同的发送的逻辑

1首先可以抽象出一个,发消息的service,添加一个发送消息方法;

public interface MessagePusher {

    /**
     * 各渠道推送消息
     * @param messageDto 最终待推送消息
     */
    void push(MessageDto messageDto);
}

2然后可以创建一个抽象类,去实现这个接口,做一些处理数据的方法

public abstract class AbstractPusher implements MessagePusher {

    @Autowired
    private MsgSendProcessorManager processorManager;

    @Autowired
    private MessageConverter converter;

    @Autowired
    protected PushMessageProcessService pushMessageProcessService;

    @Override
    public void push(MessageDto messageDto) {
        try {
            processorManager.execute(converter.convertMessageForPush(messageDto));
        } catch (BusinessException e) {
            log.error("push处理器异常", e);
            pushMessageProcessService.updatePushMessageState(messageDto.getOriginMessageId(), messageDto.getNotifyChannel(), messageDto.getDuid(), e.getCode());
            return;
        }
        doPush(messageDto);
    }

    protected abstract void doPush(MessageDto messageDto);
}

3,接下来就是写具体的发送消息的实现逻辑,可以加自定义注解,来标识具体是哪一个发送类型

@NotifyChannel(value = HC_APP)
@Service("atreusAppMessagePusher")
@Slf4j
public class AtreusAppMessagePusherImpl extends AbstractPusher {
    }
}

接下来就是怎么使用到对应的实现

可以写一个生产MessagePusher的工厂类,实现applicationContextAware

@Component
public class MessagePusherFactory implements ApplicationContextAware {

    public static final Map<NotifyChannelEnum, MessagePusher> pusherMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansWithAnnotation(NotifyChannel.class).entrySet().iterator().forEachRemaining(x ->
                pusherMap.put(x.getValue().getClass().getAnnotation(NotifyChannel.class).value(), (MessagePusher) x.getValue()));
    }

    public MessagePusher getPusher(Integer channel) {
        return pusherMap.get(NotifyChannelEnum.getByCode(channel));
    }

}

根据自定义注解的内容,来获取对应的bean,然后走到对应的实现;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值