io.github.aooohan.mq.core.DefaultRedisMqPublisher Maven / Gradle / Ivy
/*
* Copyright 2023 [lihan [email protected]]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.aooohan.mq.core;
import io.github.aooohan.mq.entity.MsgDeliver;
import io.github.aooohan.mq.serializer.RedisMqSerializer;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* @author : lihan
* @date : 2023/6/22 13:08
*/
public class DefaultRedisMqPublisher implements RedisMqPublisher {
private final RedisMqSerializer redisMqSerializer;
private final StringRedisTemplate redisTemplate;
public DefaultRedisMqPublisher(RedisMqSerializer redisMqSerializer, RedisConnectionFactory redisConnectionFactory) {
this(redisMqSerializer, new StringRedisTemplate(redisConnectionFactory));
}
public DefaultRedisMqPublisher(RedisMqSerializer redisMqSerializer, StringRedisTemplate redisMqTemplate) {
this.redisMqSerializer = redisMqSerializer;
this.redisTemplate = redisMqTemplate;
}
@Override
public String publish(String topic, Object message) {
MsgDeliver msgDeliver;
if (message instanceof MsgDeliver) {
msgDeliver = (MsgDeliver) message;
msgDeliver.incrDeliveryCount();
} else {
String payload = null;
try {
payload = redisMqSerializer.serialize(message);
} catch (Exception e) {
throw new RuntimeException(e);
}
msgDeliver = new MsgDeliver(null, payload, "1");
}
Map map = msgDeliver.toRedisMsgBody();
RecordId id = redisTemplate.opsForStream().add(MapRecord.create(topic, map));
if (id == null) {
return null;
}
return id.getValue();
}
}