package com.qiaoba.common.database.listener;

import cn.hutool.json.JSONUtil;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.database.entity.DynamicDataSource;
import com.qiaoba.common.database.util.DatasourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 切换主要的数据源
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/7/17 10:56
 */
@Component
@Slf4j
public class SwitchPrimaryListener implements MessageListener {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msgObj = redisTemplate.getValueSerializer().deserialize(messageBody);
        if (Objects.nonNull(msgObj)) {
            DynamicDataSource dynamicDataSource = JSONUtil.toBean(msgObj.toString(), DynamicDataSource.class);
            if (!BaseConstant.SERVER_SN.equals(dynamicDataSource.getServerSn())) {
                String tenantId = dynamicDataSource.getTenantId();
                log.info("切换租户主数据源, 租户ID:{}, 数据源Url:{}", tenantId, dynamicDataSource.getUrl());
                // 删除原有数据源
                DatasourceUtil.removePrimaryDatasource(tenantId);
                // 切换数据源
                DatasourceUtil.changePrimaryDatasource(tenantId, DatasourceUtil.buildDataSource(tenantId, dynamicDataSource));
            }
        }
    }

}
