使用场景
- 消费消息队列MQ的消息,持久化到DB时。
- 可能会有并发操作的业务中。
Java 核心代码示例
import com.search.dao.mapper.DomainMapper;
import com.search.domain.Domain;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;
@Service
@Slf4j
public class FenceSupplyService {
public static final int MAX_TRY_UPDATE_TIMES = 50;
@Resource
private DomainMapper mapper;
public void saveOrUpdate(Domain newDo) {
if (Objects.isNull(newDo)) {
return;
}
Domain oldDo = mapper.