Search in sources :

Example 1 with DS

use of com.baomidou.dynamic.datasource.annotation.DS in project dynamic-datasource-samples by dynamic-datasource.

the class AccountServiceImpl method reduceBalance.

/**
 * 事务传播特性设置为 REQUIRES_NEW 开启新的事务
 */
@DS("account")
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void reduceBalance(Long userId, Double price) {
    log.info("=============ACCOUNT START=================");
    log.info("当前 XID: {}", RootContext.getXID());
    Account account = accountMapper.selectById(userId);
    Assert.notNull(account, "用户不存在");
    Double balance = account.getBalance();
    log.info("下单用户{}余额为 {},商品总价为{}", userId, balance, price);
    if (balance < price) {
        log.warn("用户 {} 余额不足,当前余额:{}", userId, balance);
        throw new RuntimeException("余额不足");
    }
    log.info("开始扣减用户 {} 余额", userId);
    double currentBalance = account.getBalance() - price;
    account.setBalance(currentBalance);
    accountMapper.updateById(account);
    log.info("扣减用户 {} 余额成功,扣减后用户账户余额为{}", userId, currentBalance);
    log.info("=============ACCOUNT END=================");
}
Also used : Account(com.baomidou.samples.seata.entity.Account) DS(com.baomidou.dynamic.datasource.annotation.DS) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with DS

use of com.baomidou.dynamic.datasource.annotation.DS in project dynamic-datasource-samples by dynamic-datasource.

the class OrderServiceImpl method placeOrder.

@DS("order")
@Override
@Transactional
@GlobalTransactional
public void placeOrder(PlaceOrderRequest request) {
    log.info("=============ORDER START=================");
    Long userId = request.getUserId();
    Long productId = request.getProductId();
    Integer amount = request.getAmount();
    log.info("收到下单请求,用户:{}, 商品:{},数量:{}", userId, productId, amount);
    log.info("当前 XID: {}", RootContext.getXID());
    Order order = Order.builder().userId(userId).productId(productId).status(OrderStatus.INIT).amount(amount).build();
    orderMapper.insert(order);
    log.info("订单一阶段生成,等待扣库存付款中");
    // 扣减库存并计算总价
    Double totalPrice = productService.reduceStock(productId, amount);
    // 扣减余额
    accountService.reduceBalance(userId, totalPrice);
    order.setStatus(OrderStatus.SUCCESS);
    order.setTotalPrice(totalPrice);
    orderMapper.updateById(order);
    log.info("订单已成功下单");
    log.info("=============ORDER END=================");
}
Also used : Order(com.baomidou.samples.seata.entity.Order) GlobalTransactional(io.seata.spring.annotation.GlobalTransactional) DS(com.baomidou.dynamic.datasource.annotation.DS) GlobalTransactional(io.seata.spring.annotation.GlobalTransactional) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with DS

use of com.baomidou.dynamic.datasource.annotation.DS in project dynamic-datasource-samples by dynamic-datasource.

the class AccountService method reduceBalance.

@DS("account")
public void reduceBalance(Long userId, Double price) {
    log.info("=============ACCOUNT START=================");
    log.info("当前 XID: {}", TransactionContext.getXID());
    Account account = accountMapper.selectById(userId);
    Assert.notNull(account, "用户不存在");
    Double balance = account.getBalance();
    log.info("下单用户{}余额为 {},商品总价为{}", userId, balance, price);
    if (balance < price) {
        log.warn("用户 {} 余额不足,当前余额:{}", userId, balance);
        throw new RuntimeException("余额不足");
    }
    log.info("开始扣减用户 {} 余额", userId);
    double currentBalance = account.getBalance() - price;
    account.setBalance(currentBalance);
    accountMapper.updateById(account);
    log.info("扣减用户 {} 余额成功,扣减后用户账户余额为{}", userId, currentBalance);
    log.info("=============ACCOUNT END=================");
}
Also used : Account(com.baomidou.samples.localtx.entity.Account) DS(com.baomidou.dynamic.datasource.annotation.DS)

Example 4 with DS

use of com.baomidou.dynamic.datasource.annotation.DS in project dynamic-datasource-samples by dynamic-datasource.

the class ProductService method reduceStock.

@DS("product")
public Double reduceStock(Long productId, Integer amount) {
    log.info("=============PRODUCT START=================");
    log.info("当前 XID: {}", TransactionContext.getXID());
    // 检查库存
    Product product = productMapper.selectById(productId);
    Assert.notNull(product, "商品不存在");
    Integer stock = product.getStock();
    log.info("商品编号为 {} 的库存为{},订单商品数量为{}", productId, stock, amount);
    if (stock < amount) {
        log.warn("商品编号为{} 库存不足,当前库存:{}", productId, stock);
        throw new RuntimeException("库存不足");
    }
    log.info("开始扣减商品编号为 {} 库存,单价商品价格为{}", productId, product.getPrice());
    // 扣减库存
    int currentStock = stock - amount;
    product.setStock(currentStock);
    productMapper.updateById(product);
    double totalPrice = product.getPrice() * amount;
    log.info("扣减商品编号为 {} 库存成功,扣减后库存为{}, {} 件商品总价为 {} ", productId, currentStock, amount, totalPrice);
    log.info("=============PRODUCT END=================");
    return totalPrice;
}
Also used : Product(com.baomidou.samples.localtx.entity.Product) DS(com.baomidou.dynamic.datasource.annotation.DS)

Example 5 with DS

use of com.baomidou.dynamic.datasource.annotation.DS in project longmarch by yuyueqty.

the class SysTableBodyServiceImpl method exportData.

@DS("master")
@SuppressWarnings("unchecked")
@Override
public void exportData(String code, String dataSource, Map<String, Object> params, HttpServletResponse response, HttpServletRequest request) {
    SysTableBody sysTableBody = getSysTableBody(code);
    List<SysTableTitle> sysTableTitles = sysTableTitleService.tableTitleList(sysTableBody.getId());
    if (CollectionUtil.isEmpty(sysTableTitles)) {
        throw new BusinessException(5000, "统计SQL未配置字段");
    }
    List<ExcelExportEntity> exportEntityList = sysTableTitles.stream().map(e -> new ExcelExportEntity(e.getLabel(), e.getField())).collect(Collectors.toList());
    Map<String, Object> newParams = PageFactory.buildMap(dataSource, params);
    String cacheKey = getCacheKey(STATISTICS_EXPORT, code, newParams.toString());
    Object data = CacheUtil.get(cacheKey);
    List<LinkedHashMap<String, Object>> mapList = null;
    if (data != null && IS_CACHE) {
        mapList = (List<LinkedHashMap<String, Object>>) data;
    } else {
        try {
            switchingDataSource(dataSource, sysTableBody.getDataSource());
            mapList = sysAutoMapper.list(newParams, sysTableBody.getSqlText());
            if (CollectionUtil.isNotEmpty(mapList)) {
                CacheUtil.put(cacheKey, mapList, TIME_OUT);
            }
        } catch (Exception ignored) {
        // TODO do nothing
        }
    }
    if (mapList != null && mapList.size() > 0) {
        ExportParams exportParams = new ExportParams(sysTableBody.getLabel(), sysTableBody.getLabel());
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, exportEntityList, mapList);
        DownLoadUtil.downLoad(response, request, workbook, sysTableBody.getCode());
    }
}
Also used : java.util(java.util) ExcelExportUtil(cn.afterturn.easypoi.excel.ExcelExportUtil) ExportParams(cn.afterturn.easypoi.excel.entity.ExportParams) PersistenceException(org.apache.ibatis.exceptions.PersistenceException) BusinessException(top.longmarch.lmcore.exception.BusinessException) PageFactory(top.longmarch.lmcore.common.PageFactory) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TableTitleDTO(top.longmarch.lmsys.dto.TableTitleDTO) SysAutoMapper(top.longmarch.lmsys.mapper.SysAutoMapper) DS(com.baomidou.dynamic.datasource.annotation.DS) LambdaQueryWrapper(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper) DynamicRoutingDataSource(com.baomidou.dynamic.datasource.DynamicRoutingDataSource) DownLoadUtil(top.longmarch.lmcore.utils.upload.DownLoadUtil) Function(java.util.function.Function) ISysTableRelService(top.longmarch.lmsys.service.ISysTableRelService) MD5(cn.hutool.crypto.digest.MD5) JSONUtil(cn.hutool.json.JSONUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) Service(org.springframework.stereotype.Service) TableTitleVO(top.longmarch.lmsys.vo.TableTitleVO) ServiceImpl(com.baomidou.mybatisplus.extension.service.impl.ServiceImpl) Wrappers(com.baomidou.mybatisplus.core.toolkit.Wrappers) ExcelExportEntity(cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity) CollectionUtil(cn.hutool.core.collection.CollectionUtil) SysTableTitle(top.longmarch.lmsys.entity.SysTableTitle) ISysTableTitleService(top.longmarch.lmsys.service.ISysTableTitleService) CacheUtil(top.longmarch.lmcore.cache.CacheUtil) ExcelType(cn.afterturn.easypoi.excel.entity.enmus.ExcelType) HttpServletResponse(javax.servlet.http.HttpServletResponse) ISysTableBodyService(top.longmarch.lmsys.service.ISysTableBodyService) Collectors(java.util.stream.Collectors) SearchSuper(top.longmarch.lmcore.common.SearchSuper) Page(com.baomidou.mybatisplus.extension.plugins.pagination.Page) StrUtil(cn.hutool.core.util.StrUtil) Slf4j(lombok.extern.slf4j.Slf4j) Workbook(org.apache.poi.ss.usermodel.Workbook) DynamicDataSourceContextHolder(com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder) SysTableRel(top.longmarch.lmsys.entity.SysTableRel) SysTableBodyMapper(top.longmarch.lmsys.mapper.SysTableBodyMapper) Data(lombok.Data) JSONArray(cn.hutool.json.JSONArray) IPage(com.baomidou.mybatisplus.core.metadata.IPage) SysTableBody(top.longmarch.lmsys.entity.SysTableBody) SysTableTitle(top.longmarch.lmsys.entity.SysTableTitle) ExcelExportEntity(cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity) PersistenceException(org.apache.ibatis.exceptions.PersistenceException) BusinessException(top.longmarch.lmcore.exception.BusinessException) Workbook(org.apache.poi.ss.usermodel.Workbook) SysTableBody(top.longmarch.lmsys.entity.SysTableBody) ExportParams(cn.afterturn.easypoi.excel.entity.ExportParams) BusinessException(top.longmarch.lmcore.exception.BusinessException) DS(com.baomidou.dynamic.datasource.annotation.DS)

Aggregations

DS (com.baomidou.dynamic.datasource.annotation.DS)12 Transactional (org.springframework.transaction.annotation.Transactional)6 PersistenceException (org.apache.ibatis.exceptions.PersistenceException)3 GlobalTransactional (io.seata.spring.annotation.GlobalTransactional)2 BusinessException (top.longmarch.lmcore.exception.BusinessException)2 SysTableBody (top.longmarch.lmsys.entity.SysTableBody)2 ExcelExportUtil (cn.afterturn.easypoi.excel.ExcelExportUtil)1 ExportParams (cn.afterturn.easypoi.excel.entity.ExportParams)1 ExcelType (cn.afterturn.easypoi.excel.entity.enmus.ExcelType)1 ExcelExportEntity (cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity)1 CollectionUtil (cn.hutool.core.collection.CollectionUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 MD5 (cn.hutool.crypto.digest.MD5)1 JSONArray (cn.hutool.json.JSONArray)1 JSONUtil (cn.hutool.json.JSONUtil)1 DynamicRoutingDataSource (com.baomidou.dynamic.datasource.DynamicRoutingDataSource)1 DynamicDataSourceContextHolder (com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder)1 LambdaQueryWrapper (com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper)1 IPage (com.baomidou.mybatisplus.core.metadata.IPage)1 Wrappers (com.baomidou.mybatisplus.core.toolkit.Wrappers)1