Commit b7808dae by 章家宝

需求:明拍新增轮询出价代码提交

1 parent 1b61bb04
Showing 29 changed files with 1121 additions and 28 deletions
package com.glsx.usedcar.web.rest.auction; package com.glsx.usedcar.web.rest.auction;
import com.glsx.usedcar.module.analysis.domain.AuctionVehicleRate; import com.glsx.usedcar.module.analysis.domain.AuctionVehicleRate;
import com.glsx.usedcar.module.auction.domain.AuctionControl; import com.glsx.usedcar.module.auction.domain.*;
import com.glsx.usedcar.module.auction.domain.AuctionVehicleAddon;
import com.glsx.usedcar.module.auction.domain.PendingAuction;
import com.glsx.usedcar.module.auction.entity.*; import com.glsx.usedcar.module.auction.entity.*;
import com.glsx.usedcar.module.auction.entity.dto.BidRemainSecondDTO;
import com.glsx.usedcar.module.auction.entity.vo.BidEndTimeVO;
import com.glsx.usedcar.module.auction.service.AuctionChangeService; import com.glsx.usedcar.module.auction.service.AuctionChangeService;
import com.glsx.usedcar.module.auction.service.AuctionOrderService;
import com.glsx.usedcar.module.auction.service.AuctionService; import com.glsx.usedcar.module.auction.service.AuctionService;
import com.glsx.usedcar.module.meta.AuditState; import com.glsx.usedcar.module.meta.AuditState;
import com.glsx.usedcar.module.security.entity.User; import com.glsx.usedcar.module.security.entity.User;
import com.glsx.usedcar.module.track.entity.ApproveHistory; import com.glsx.usedcar.module.track.entity.ApproveHistory;
import com.glsx.usedcar.module.track.service.TrackService; import com.glsx.usedcar.module.track.service.TrackService;
import com.glsx.usedcar.resp.BaseResp;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import jakarta.validation.Valid; import jakarta.validation.Valid;
...@@ -276,4 +276,10 @@ public class AuctionController { ...@@ -276,4 +276,10 @@ public class AuctionController {
auctionService.addAuctionVehicles(auctionVehicleAddon); auctionService.addAuctionVehicles(auctionVehicleAddon);
return auctionVehicleAddon.getAuctionId(); return auctionVehicleAddon.getAuctionId();
} }
@PostMapping("getBidRemainSec")
public BaseResp<BidRemainSecondDTO> getBidRemainSec(@RequestBody BidEndTimeVO bidEndTimeVO) throws FieldException {
return auctionService.getBidRemainSec(bidEndTimeVO);
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -3,15 +3,20 @@ package com.glsx.usedcar.web.rest.auction; ...@@ -3,15 +3,20 @@ package com.glsx.usedcar.web.rest.auction;
import com.glsx.usedcar.module.analysis.domain.IndexValue; import com.glsx.usedcar.module.analysis.domain.IndexValue;
import com.glsx.usedcar.module.auction.entity.Bid; import com.glsx.usedcar.module.auction.entity.Bid;
import com.glsx.usedcar.module.auction.entity.Bid_; import com.glsx.usedcar.module.auction.entity.Bid_;
import com.glsx.usedcar.module.auction.entity.vo.BidAddVO;
import com.glsx.usedcar.module.auction.service.BidService; import com.glsx.usedcar.module.auction.service.BidService;
import com.glsx.usedcar.module.security.entity.User;
import com.glsx.usedcar.resp.BaseResp;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.persistence.criteria.JoinType; import jakarta.persistence.criteria.JoinType;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page; import org.summerframework.core.exception.FieldException;
import org.summerframework.orm.paging.Pagination; import org.summerframework.orm.paging.Pagination;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -84,5 +89,16 @@ public class BidController { ...@@ -84,5 +89,16 @@ public class BidController {
return Map.of("minuteCount", minuteCount, "hourCount", hourCount); return Map.of("minuteCount", minuteCount, "hourCount", hourCount);
} }
/**
* 新增投标竞价
*
* @param bidRequest
* @return
*/
@PostMapping("addBid")
public BaseResp<Bid> addBid(@Valid @RequestBody BidAddVO bidAddVO, Authentication authentication) throws FieldException {
User user = (User) authentication.getPrincipal();
return BaseResp.success(bidService.addBidByAdmin(user, bidAddVO));
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -11,7 +11,9 @@ import com.glsx.usedcar.module.vehicle.domain.VehicleHistoryProjection; ...@@ -11,7 +11,9 @@ import com.glsx.usedcar.module.vehicle.domain.VehicleHistoryProjection;
import com.glsx.usedcar.module.vehicle.domain.VehicleVenue; import com.glsx.usedcar.module.vehicle.domain.VehicleVenue;
import com.glsx.usedcar.module.vehicle.entity.Vehicle; import com.glsx.usedcar.module.vehicle.entity.Vehicle;
import com.glsx.usedcar.module.vehicle.entity.Vehicle_; import com.glsx.usedcar.module.vehicle.entity.Vehicle_;
import com.glsx.usedcar.module.vehicle.entity.vo.VehicleAutoBidVO;
import com.glsx.usedcar.module.vehicle.service.VehicleService; import com.glsx.usedcar.module.vehicle.service.VehicleService;
import com.glsx.usedcar.resp.BaseResp;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.persistence.criteria.*; import jakarta.persistence.criteria.*;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
...@@ -28,9 +30,7 @@ import org.summerframework.storage.domain.FileInfo; ...@@ -28,9 +30,7 @@ import org.summerframework.storage.domain.FileInfo;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.*;
import java.util.Map;
import java.util.Objects;
/** /**
...@@ -284,4 +284,16 @@ public class VehicleController { ...@@ -284,4 +284,16 @@ public class VehicleController {
ExcelExporter.exportExcel(response, "评估定价车辆列表", "车辆列表", VehicleBean.class, vehicleBeans); ExcelExporter.exportExcel(response, "评估定价车辆列表", "车辆列表", VehicleBean.class, vehicleBeans);
} }
/**
* 系统自动加价
*
* @param vehicleAutoBidVO 自动加价参数
* @return true 添加成功 false 添加失败
*/
@PostMapping("autoBid")
public BaseResp<Boolean> autoBid(@RequestBody VehicleAutoBidVO vehicleAutoBidVO) {
return vehicleService.autoBid(vehicleAutoBidVO);
}
} }
\ No newline at end of file \ No newline at end of file
...@@ -94,7 +94,7 @@ public class BidController { ...@@ -94,7 +94,7 @@ public class BidController {
*/ */
@PostMapping("addBid") @PostMapping("addBid")
public Bid addBid(@Valid @RequestBody BidRequest bidRequest, @RequestAttribute(LOGIN_ACCOUNT) Account account) throws FieldException { public Bid addBid(@Valid @RequestBody BidRequest bidRequest, @RequestAttribute(LOGIN_ACCOUNT) Account account) throws FieldException {
return bidService.addBid(account.getAccountId(), bidRequest.getAucvehId(), bidRequest.getBidPrice()); return bidService.addBidByAccount(account.getAccountId(), bidRequest.getAucvehId(), bidRequest.getBidPrice());
} }
@GetMapping("getBidsByAuctionVehicle") @GetMapping("getBidsByAuctionVehicle")
......
package com.glsx.usedcar.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 自定义异步线程池配置
*/
@Configuration
public class AsyncThreadPoolConfig {
/**
* 自动竞价线程池
*/
@Bean(name = "auctionAutoBiddingExecutor")
public Executor auctionCoreExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 1. 核心线程数(常驻线程):根据CPU核心数/业务量调整,比如8核CPU设为8-16
executor.setCorePoolSize(10);
// 2. 最大线程数:核心线程忙且队列满时,最多创建的线程数
executor.setMaxPoolSize(20);
// 3. 队列容量:核心线程忙时,任务先进入队列等待
executor.setQueueCapacity(100);
// 4. 线程名前缀:便于日志排查(比如"auction-core-1")
executor.setThreadNamePrefix("auction-auto-bidding-");
// 5. 空闲线程存活时间:超出核心线程数的线程,空闲多久销毁(单位:秒)
executor.setKeepAliveSeconds(60);
// 6. 拒绝策略:队列满+最大线程数已满时,如何处理新任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化线程池
executor.initialize();
return executor;
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis核心配置:优化序列化方式
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 1. 配置Key序列化:字符串序列化(必选,保证key可读)
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// 2. 配置Value序列化:JSON序列化(支持复杂对象、Java8时间类型)
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
// 开启所有字段的序列化(包括private)
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 开启类型信息(反序列化时能还原为原对象类型)
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
// 注册Java8时间类型序列化器(解决LocalDateTime等序列化问题)
objectMapper.registerModule(new JavaTimeModule());
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
// 初始化模板
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
\ No newline at end of file \ No newline at end of file
...@@ -45,6 +45,16 @@ public interface AuctionDao extends BaseRepository<Auction, Integer>, JpaSpecifi ...@@ -45,6 +45,16 @@ public interface AuctionDao extends BaseRepository<Auction, Integer>, JpaSpecifi
*/ */
List<Auction> findByAuctionStateAndAuctionEndTimeIsBefore(Auction.AuctionState auctionState, LocalDateTime nowTime); List<Auction> findByAuctionStateAndAuctionEndTimeIsBefore(Auction.AuctionState auctionState, LocalDateTime nowTime);
/**
* 查询已经开始的所有场次
*
* @param auctionState
* @param nowTime
* @return
*/
List<Auction> findByAuctionStateAndAuctionTypeAndAuctionMode(Auction.AuctionState auctionState, Auction.AuctionType auctionType, int auctionMode);
List<Auction> findByAuctionStateOrderByAuctionNameAsc(Auction.AuctionState auctionState); List<Auction> findByAuctionStateOrderByAuctionNameAsc(Auction.AuctionState auctionState);
List<Auction> findTop3ByAuctionStateOrderByAuctionStartTimeDesc(Auction.AuctionState auctionState); List<Auction> findTop3ByAuctionStateOrderByAuctionStartTimeDesc(Auction.AuctionState auctionState);
......
...@@ -183,6 +183,18 @@ public class Auction extends AuditingEntity implements Serializable { ...@@ -183,6 +183,18 @@ public class Auction extends AuditingEntity implements Serializable {
@Column @Column
private double transactionVolume; private double transactionVolume;
/**
* 扩展字段
*/
@Column
private String extraJson;
/**
* 如果是明拍,那么1 是普通模式, 2 是轮询出价模式,如果是暗拍,字段暂时无效
*/
@Column
private Integer auctionMode;
/** /**
* 访问范围 * 访问范围
......
...@@ -58,9 +58,8 @@ public class Bid extends AuditingTimeEntity implements Serializable { ...@@ -58,9 +58,8 @@ public class Bid extends AuditingTimeEntity implements Serializable {
/** /**
* ACCOUNT_ID * ACCOUNT_ID
*/ */
@NotNull
@ManyToOne(cascade = {}, fetch = FetchType.LAZY) @ManyToOne(cascade = {}, fetch = FetchType.LAZY)
@JoinColumns({@JoinColumn(name = "ACCOUNT_ID", nullable = false)}) @JoinColumns({@JoinColumn(name = "ACCOUNT_ID")})
private Account account; private Account account;
/** /**
...@@ -83,6 +82,18 @@ public class Bid extends AuditingTimeEntity implements Serializable { ...@@ -83,6 +82,18 @@ public class Bid extends AuditingTimeEntity implements Serializable {
private boolean deal; private boolean deal;
/** /**
* 0 个人用户 1 系统加价助手 2 后台人员加价
*/
@Column(nullable = false)
private Integer bidType;
/**
* 后台人员id 当前是后台人员加价时使用
*/
@Column(nullable = true)
private Integer userId;
/**
* 延时结束时间 * 延时结束时间
*/ */
@Transient @Transient
......
package com.glsx.usedcar.module.auction.entity.dto;
import lombok.*;
/**
*
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class BidRemainSecondDTO {
// 投标剩余时间
private double remainSecond;
}
package com.glsx.usedcar.module.auction.entity.dto;
import lombok.*;
/**
* 明拍轮询出价配置
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LightPollingBidConfigDTO {
// 结束后自动延迟切换下一辆车的时间,单位秒
private Integer delay;
// 接近保留价提醒阈值
private Integer nearReservePriceThreshold;
// 加价重置延迟 单位 秒
private Integer resetDelay;
// 在时间内加价才会触发延迟 单位 秒
private Integer resetDelayDuration;
// 车辆拍卖持续时间
private Integer aucvehDuration;
}
package com.glsx.usedcar.module.auction.entity.vo;
import jakarta.validation.constraints.NotNull;
import lombok.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BidAddVO {
@NotNull
private Integer aucvehId;
/**
* 出价金额
*/
@NotNull
private Integer bidPrice;
}
package com.glsx.usedcar.module.auction.entity.vo;
import lombok.Data;
@Data
public class BidEndTimeVO {
private int aucvehId;
}
package com.glsx.usedcar.module.auction.entity.vo;
import lombok.*;
import java.math.BigDecimal;
/**
* 明拍竞价时间和价格
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LightAuctionPoolingBidTimeAndPriceVO {
// 当前最新价格
private BigDecimal price;
// 剩余时间 单位秒
private double remainSecond;
// 是否结束
private boolean isOver;
// 是否接近保留价
private boolean isNearReservePrice;
// 是否大幅度加价
private boolean isSignificantPriceIncrease;
private BigDecimal accountBidPrice;
}
package com.glsx.usedcar.module.auction.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 投标竞价类型
*/
@Getter
@AllArgsConstructor
public enum BidTypeEnum {
BID_ACCOUNT(0, "用户竞价"),
BID_SYSTEM(1, "系统加价"),
BID_ADMIN(2, "管理员加价"),
;
private final int code;
private final String desc;
}
...@@ -3,23 +3,23 @@ package com.glsx.usedcar.module.auction.service; ...@@ -3,23 +3,23 @@ package com.glsx.usedcar.module.auction.service;
import com.glsx.usedcar.module.account.dao.AccountDao; import com.glsx.usedcar.module.account.dao.AccountDao;
import com.glsx.usedcar.module.account.entity.Account; import com.glsx.usedcar.module.account.entity.Account;
import com.glsx.usedcar.module.analysis.domain.IndexValue; import com.glsx.usedcar.module.analysis.domain.IndexValue;
import com.glsx.usedcar.module.auction.dao.AuctionOrderDao; import com.glsx.usedcar.module.auction.dao.*;
import com.glsx.usedcar.module.auction.dao.AuctionVehicleDao;
import com.glsx.usedcar.module.auction.dao.BidDao;
import com.glsx.usedcar.module.auction.domain.BidStat; import com.glsx.usedcar.module.auction.domain.BidStat;
import com.glsx.usedcar.module.auction.entity.Auction; import com.glsx.usedcar.module.auction.entity.*;
import com.glsx.usedcar.module.auction.entity.AuctionOrder; import com.glsx.usedcar.module.auction.entity.Auction.AuctionType;
import com.glsx.usedcar.module.auction.entity.AuctionVehicle; import com.glsx.usedcar.module.auction.entity.vo.BidAddVO;
import com.glsx.usedcar.module.auction.entity.Bid; import com.glsx.usedcar.module.auction.enums.BidTypeEnum;
import com.glsx.usedcar.module.finance.dao.DepositDao; import com.glsx.usedcar.module.finance.dao.*;
import com.glsx.usedcar.module.finance.dao.TransactionDao;
import com.glsx.usedcar.module.finance.dao.WithdrawDao;
import com.glsx.usedcar.module.finance.entity.Deposit; import com.glsx.usedcar.module.finance.entity.Deposit;
import com.glsx.usedcar.module.finance.entity.Transaction; import com.glsx.usedcar.module.finance.entity.Transaction;
import com.glsx.usedcar.module.meta.AuditState; import com.glsx.usedcar.module.meta.AuditState;
import com.glsx.usedcar.module.security.dao.UserDao;
import com.glsx.usedcar.module.security.entity.User;
import com.glsx.usedcar.util.CoderGenerator; import com.glsx.usedcar.util.CoderGenerator;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.ObjectNotFoundException; import org.hibernate.ObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
...@@ -29,14 +29,14 @@ import org.summerframework.orm.paging.Pagination; ...@@ -29,14 +29,14 @@ import org.summerframework.orm.paging.Pagination;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.*;
import java.util.Objects;
/** /**
* 投标竞价(Bid) 服务实现类 * 投标竞价(Bid) 服务实现类
* *
* @since 2025-10-13 12:18:11 * @since 2025-10-13 12:18:11
*/ */
@Slf4j
@Service @Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class BidService { public class BidService {
...@@ -56,6 +56,10 @@ public class BidService { ...@@ -56,6 +56,10 @@ public class BidService {
private AuctionOrderDao auctionOrderDao; private AuctionOrderDao auctionOrderDao;
@Resource @Resource
private WithdrawDao withdrawDao; private WithdrawDao withdrawDao;
@Autowired
private UserDao userDao;
@Autowired
private LightAuctionPoollingBidService lightAuctionPoollingBidService;
/** /**
...@@ -74,7 +78,25 @@ public class BidService { ...@@ -74,7 +78,25 @@ public class BidService {
* @return 投标竞价列表 * @return 投标竞价列表
*/ */
public Page<Bid> pageBid(Pagination<Bid> pagination) { public Page<Bid> pageBid(Pagination<Bid> pagination) {
return bidDao.findAll(pagination, pagination.getPageRequest()); Page<Bid> page = bidDao.findAll(pagination, pagination.getPageRequest());
Map<Integer, User> userMap = new HashMap<>();
for (Bid bid : page.getContent()) {
if (bid.getBidType() == 2 && bid.getUserId() != null && bid.getUserId() > 0) {
User user = userMap.get(bid.getUserId());
if (user == null) {
user = userDao.findByUserId(bid.getUserId());
}
if (user != null) {
userMap.put(bid.getUserId(), user);
Account account = new Account();
account.setMobile(user.getMobile());
account.setNickName(user.getUserName());
account.setAccountName(user.getUserName());
bid.setAccount(account);
}
}
}
return page;
} }
public BidStat getBidStatByAuctionId(int auctionId, int accountId) { public BidStat getBidStatByAuctionId(int auctionId, int accountId) {
...@@ -102,7 +124,7 @@ public class BidService { ...@@ -102,7 +124,7 @@ public class BidService {
* @return 投标竞价实例对象 * @return 投标竞价实例对象
*/ */
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bid addBid(int accountId, int aucvehId, int bidPrice) throws FieldException { public Bid addBidByAccount(int accountId, int aucvehId, int bidPrice) throws FieldException {
AuctionVehicle auctionVehicle = auctionVehicleDao.findTopByAucvehId(aucvehId); AuctionVehicle auctionVehicle = auctionVehicleDao.findTopByAucvehId(aucvehId);
if (auctionVehicle.getAuctionState() != AuctionVehicle.AuctionState.AUCTIONING) { if (auctionVehicle.getAuctionState() != AuctionVehicle.AuctionState.AUCTIONING) {
throw new FieldException("aucvehId", aucvehId, "该车辆已结束竞标"); throw new FieldException("aucvehId", aucvehId, "该车辆已结束竞标");
...@@ -144,6 +166,35 @@ public class BidService { ...@@ -144,6 +166,35 @@ public class BidService {
depositDao.save(deposit); depositDao.save(deposit);
} }
return addBid(bidPrice, auctionVehicle, auction, account, BidTypeEnum.BID_ACCOUNT, null);
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bid addBidBySystem(int aucvehId, int bidPrice) throws FieldException {
AuctionVehicle auctionVehicle = auctionVehicleDao.findTopByAucvehId(aucvehId);
if (auctionVehicle.getAuctionState() != AuctionVehicle.AuctionState.AUCTIONING) {
log.info("{} {} {} 该车辆已结束竞标", auctionVehicle.getAuction().getAuctionId(), aucvehId, auctionVehicle.getAuction().getAuctionName());
throw new FieldException("aucvehId", aucvehId, "该车辆已结束竞标");
}
return addBid(bidPrice, auctionVehicle, auctionVehicle.getAuction(), null, BidTypeEnum.BID_ADMIN, null);
}
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Bid addBidByAdmin(User user, BidAddVO bidAddVO) throws FieldException {
int aucvehId = bidAddVO.getAucvehId();
AuctionVehicle auctionVehicle = auctionVehicleDao.findTopByAucvehId(aucvehId);
Auction auction = auctionVehicle.getAuction();
if (auctionVehicle.getAuctionState() != AuctionVehicle.AuctionState.AUCTIONING) {
log.info("{} {} {} 该车辆已结束竞标", auction.getAuctionId(), aucvehId, auctionVehicle.getAuction().getAuctionName());
throw new FieldException("aucvehId", aucvehId, "该车辆已结束竞标");
}
if (auction.getAuctionType() != AuctionType.LIGHT && auction.getAuctionMode() != 2) {
log.info("{} {} {} {}该拍场不适用后台出价", auction.getAuctionId(), user.getUserId(), auction.getAuctionType(), auction.getAuctionMode());
throw new FieldException("aucvehId", aucvehId, "该拍场不适用后台出价");
}
return addBid(bidAddVO.getBidPrice(), auctionVehicle, auctionVehicle.getAuction(), null, BidTypeEnum.BID_ADMIN, user.getUserId());
}
private Bid addBid(int bidPrice, AuctionVehicle auctionVehicle, Auction auction, Account account, BidTypeEnum bidType, Integer userId) throws FieldException {
// 最低出价 // 最低出价
double minBidPrice = auctionVehicle.getHighestPrice(); double minBidPrice = auctionVehicle.getHighestPrice();
if (auction.getAuctionType() == Auction.AuctionType.DARK) { if (auction.getAuctionType() == Auction.AuctionType.DARK) {
...@@ -175,6 +226,8 @@ public class BidService { ...@@ -175,6 +226,8 @@ public class BidService {
bid.setBidCode(CoderGenerator.generateCode(6)); bid.setBidCode(CoderGenerator.generateCode(6));
bid.setAuctionVehicle(auctionVehicle); bid.setAuctionVehicle(auctionVehicle);
bid.setDeal(true); bid.setDeal(true);
bid.setBidType(bidType.getCode());
bid.setUserId(userId);
bid = bidDao.save(bid); bid = bidDao.save(bid);
// 设置车辆延长结束时间,用于前台更新 // 设置车辆延长结束时间,用于前台更新
bid.setAuctionEndTime(auctionEndTime); bid.setAuctionEndTime(auctionEndTime);
...@@ -185,10 +238,24 @@ public class BidService { ...@@ -185,10 +238,24 @@ public class BidService {
auctionVehicle.setBidCount((int) bidDao.countByAuctionVehicle(auctionVehicle)); auctionVehicle.setBidCount((int) bidDao.countByAuctionVehicle(auctionVehicle));
// 更新最后活跃时间 // 更新最后活跃时间
if (account != null) {
account.setLastLoginTime(LocalDateTime.now()); account.setLastLoginTime(LocalDateTime.now());
}
afterAddBid(bid, auction, auctionVehicle);
return bid; return bid;
} }
/**
* 投标竞价之后的处理
*/
private void afterAddBid(Bid bid, Auction auction, AuctionVehicle auctionVehicle) {
try {
lightAuctionPoollingBidService.afterAddBid(bid, auction, auctionVehicle);
} catch (Exception e) {
log.error("明拍轮询竞价报错", e);
}
}
/** /**
* 通过投标竞价主键删除数据 * 通过投标竞价主键删除数据
......
package com.glsx.usedcar.module.system.cache;
import com.glsx.usedcar.module.system.entity.SystemConfig;
import com.glsx.usedcar.module.system.service.SystemConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
/**
* 系统配置Redis缓存工具类
* 核心逻辑:先查Redis → 未命中查DB → 写入Redis;支持配置缓存刷新/删除
*
* @since 2026-03-03
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class SystemConfigRedisCache {
// ===================== 缓存配置常量 =====================
/**
* 系统配置缓存前缀(避免key冲突)
*/
private static final String SYSTEM_CONFIG_CACHE_PREFIX = "system:config:";
/**
* 缓存过期时间:1小时(可根据业务调整)
*/
private static final Duration CACHE_EXPIRE_TIME = Duration.ofHours(1);
/**
* 空值缓存过期时间:5分钟(避免缓存穿透)
*/
private static final Duration EMPTY_VALUE_EXPIRE_TIME = Duration.ofMinutes(5);
// ===================== 依赖注入 =====================
private final RedisTemplate<String, Object> redisTemplate;
private final SystemConfigService systemConfigService;
// ===================== 核心缓存方法 =====================
/**
* 获取字符串类型配置值(核心逻辑:先Redis后DB,自动缓存)
* @param configKey 配置键
* @param defaultValue 默认值(配置不存在/解析失败时返回)
* @return 配置值
*/
public String getConfigValueAsString(String configKey, String defaultValue) {
if (!StringUtils.hasText(configKey)) {
log.warn("配置键为空,返回默认值:{}", defaultValue);
return defaultValue;
}
// 1. 拼接缓存Key
String cacheKey = buildCacheKey(configKey);
// 2. 先查Redis缓存
Object cacheValue = redisTemplate.opsForValue().get(cacheKey);
if (cacheValue != null) {
// 处理空值缓存(避免缓存穿透)
if ("__EMPTY__".equals(cacheValue)) {
log.debug("配置键[{}]Redis缓存为空值,返回默认值:{}", configKey, defaultValue);
return defaultValue;
}
String value = cacheValue.toString();
log.debug("从Redis获取配置[{}]成功,值:{}", configKey, value);
return value;
}
// 3. Redis未命中,查数据库
Optional<SystemConfig> configOpt = systemConfigService.getConfigByKey(configKey);
if (configOpt.isEmpty()) {
// 缓存空值(避免缓存穿透)
redisTemplate.opsForValue().set(cacheKey, "__EMPTY__", EMPTY_VALUE_EXPIRE_TIME);
log.warn("配置键[{}]数据库不存在,缓存空值并返回默认值:{}", configKey, defaultValue);
return defaultValue;
}
// 4. DB查询成功,写入Redis缓存
String configValue = configOpt.get().getConfigValue();
redisTemplate.opsForValue().set(cacheKey, configValue, CACHE_EXPIRE_TIME);
log.info("从数据库获取配置[{}]并写入Redis,值:{}", configKey, configValue);
return configValue;
}
/**
* 获取整数类型配置值(基于字符串方法封装,自动类型转换)
* @param configKey 配置键
* @param defaultValue 默认值
* @return 整数配置值
*/
public int getConfigValueAsInt(String configKey, int defaultValue) {
String strValue = getConfigValueAsString(configKey, null);
if (strValue == null) {
log.warn("配置键[{}]值为空,返回默认值:{}", configKey, defaultValue);
return defaultValue;
}
try {
return Integer.parseInt(strValue);
} catch (NumberFormatException e) {
log.error("配置键[{}]值[{}]解析为整数失败,返回默认值:{}", configKey, strValue, defaultValue, e);
return defaultValue;
}
}
/**
* 获取布尔类型配置值(基于字符串方法封装)
* @param configKey 配置键
* @param defaultValue 默认值
* @return 布尔配置值
*/
public Boolean getConfigValueAsBoolean(String configKey, Boolean defaultValue) {
String strValue = getConfigValueAsString(configKey, null);
if (strValue == null) {
log.warn("配置键[{}]值为空,返回默认值:{}", configKey, defaultValue);
return defaultValue;
}
if ("true".equalsIgnoreCase(strValue) || "1".equals(strValue)) {
return true;
} else if ("false".equalsIgnoreCase(strValue) || "0".equals(strValue)) {
return false;
} else {
log.error("配置键[{}]值[{}]解析为布尔值失败,返回默认值:{}", configKey, strValue, defaultValue);
return defaultValue;
}
}
// ===================== 缓存维护方法(配置修改/删除时调用) =====================
/**
* 刷新指定配置的缓存(配置修改后调用)
* @param configKey 配置键
*/
public void refreshConfigCache(String configKey) {
if (!StringUtils.hasText(configKey)) {
log.warn("刷新缓存失败:配置键为空");
return;
}
String cacheKey = buildCacheKey(configKey);
// 1. 先删除旧缓存
redisTemplate.delete(cacheKey);
// 2. 查DB重新写入缓存(复用核心逻辑)
getConfigValueAsString(configKey, null);
log.info("刷新配置[{}]的Redis缓存成功", configKey);
}
/**
* 删除指定配置的缓存(配置删除后调用)
* @param configKey 配置键
*/
public void removeConfigCache(String configKey) {
if (!StringUtils.hasText(configKey)) {
log.warn("删除缓存失败:配置键为空");
return;
}
String cacheKey = buildCacheKey(configKey);
Boolean deleteResult = redisTemplate.delete(cacheKey);
if (Boolean.TRUE.equals(deleteResult)) {
log.info("删除配置[{}]的Redis缓存成功", configKey);
} else {
log.warn("配置[{}]的Redis缓存不存在,无需删除", configKey);
}
}
/**
* 初始化所有启用的配置到Redis(项目启动时执行)
* 可选:若配置数量少,可启动时全量加载;数量多则按需懒加载(默认懒加载)
*/
public void initAllConfigToRedis() {
try {
// 查询所有启用且未删除的配置
List<SystemConfig> enableConfigs = systemConfigService.listConfigByStatus((byte) 1);
if (enableConfigs.isEmpty()) {
log.info("初始化系统配置缓存:无启用的配置");
return;
}
// 批量写入Redis
for (SystemConfig config : enableConfigs) {
String cacheKey = buildCacheKey(config.getConfigKey());
redisTemplate.opsForValue().set(cacheKey, config.getConfigValue(), CACHE_EXPIRE_TIME);
}
log.info("初始化系统配置缓存完成,共加载{}个启用配置", enableConfigs.size());
} catch (Exception e) {
log.error("初始化系统配置缓存失败", e);
}
}
// ===================== 私有工具方法 =====================
/**
* 构建缓存Key(拼接前缀,避免冲突)
* @param configKey 配置键
* @return 完整缓存Key
*/
private String buildCacheKey(String configKey) {
return SYSTEM_CONFIG_CACHE_PREFIX + configKey;
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.module.system.dao;
import com.glsx.usedcar.module.system.entity.SystemConfig;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.summerframework.orm.BaseRepository;
import java.util.List;
/**
* 系统配置表(SystemConfig)数据访问层
*
* @since 2026-03-03
*/
public interface SystemConfigDao extends BaseRepository<SystemConfig, Integer>, JpaSpecificationExecutor<SystemConfig> {
/**
* 根据配置键查询未删除的系统配置(configKey唯一)
*/
SystemConfig findByConfigKeyAndDeletedFlag(String configKey, String deletedFlag);
/**
* 根据状态+删除标识查询系统配置列表
* (如:查询所有启用且未删除的配置)
*/
List<SystemConfig> findByStatusAndDeletedFlag(Byte status, String deletedFlag);
/**
* 根据配置类型+删除标识查询系统配置列表
* (如:查询所有数值型且未删除的配置)
*/
List<SystemConfig> findByConfigTypeAndDeletedFlag(Byte configType, String deletedFlag);
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.module.system.entity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.summerframework.orm.entity.AuditingTimeEntity;
import java.io.Serializable;
import static jakarta.persistence.GenerationType.IDENTITY;
/**
* 系统配置表(SystemConfig)实体类
* 对应数据库表:system_config
*/
@Entity
@DynamicInsert
@DynamicUpdate
@Table(
name = "system_config",
indexes = {
// 配置键唯一索引
@Index(name = "uk_config_key", columnList = "config_key", unique = true),
// 状态索引
@Index(name = "idx_status", columnList = "status"),
// 删除标识索引
@Index(name = "idx_deleted_flag", columnList = "deleted_flag")
}
)
@EntityListeners(AuditingEntityListener.class) // 启用JPA审计监听
@Getter
@Setter
@NoArgsConstructor
@ToString(exclude = {}) // 无关联对象,无需排除
public class SystemConfig extends AuditingTimeEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false, columnDefinition = "int(11) COMMENT '主键ID'")
private Integer id;
/**
* 配置键(唯一,如:auction_auto_bid_step)
*/
@Column(
name = "config_key",
nullable = false,
length = 64,
columnDefinition = "varchar(64) COMMENT '配置键(唯一,如:auction_auto_bid_step)'"
)
private String configKey;
/**
* 配置名称(如:自动竞价加价步长)
*/
@Column(
name = "config_name",
nullable = false,
length = 128,
columnDefinition = "varchar(128) COMMENT '配置名称(如:自动竞价加价步长)'"
)
private String configName;
/**
* 配置值(存储具体值,如:100)
*/
@Column(
name = "config_value",
nullable = false,
length = 255,
columnDefinition = "varchar(255) COMMENT '配置值(存储具体值,如:100)'"
)
private String configValue;
/**
* 配置类型(1:数值型;2:字符串型;3:布尔型;4:日期型;5:JSON型)
*/
@Column(
name = "config_type",
nullable = false,
columnDefinition = "tinyint(2) COMMENT '配置类型(1:数值型;2:字符串型;3:布尔型;4:日期型;5:JSON型)'"
)
private Byte configType;
/**
* 状态(1:启用;2:禁用)
*/
@Column(
name = "status",
nullable = false,
columnDefinition = "tinyint(2) COMMENT '状态(1:启用;2:禁用)'"
)
private Byte status;
/**
* 创建人
*/
@Column(
name = "created_by",
nullable = false,
length = 64,
columnDefinition = "varchar(64) COMMENT '创建人'"
)
private String createdBy;
/**
* 修改人
*/
@Column(
name = "updated_by",
nullable = false,
length = 64,
columnDefinition = "varchar(64) COMMENT '修改人'"
)
private String updatedBy;
/**
* 删除标识(D:已删除;N:未删除)
*/
@Column(
name = "deleted_flag",
nullable = false,
length = 1,
columnDefinition = "char(1) NOT NULL DEFAULT 'N' COMMENT '删除标识(D:已删除;N:未删除)'"
)
private String deletedFlag = "N";
// ===================== 常用有参构造器 =====================
/**
* 快速创建配置的构造器(核心字段)
*/
public SystemConfig(String configKey, String configName, String configValue, Byte configType, Byte status) {
this.configKey = configKey;
this.configName = configName;
this.configValue = configValue;
this.configType = configType;
this.status = status;
this.deletedFlag = "N"; // 默认未删除
}
/**
* 完整构造器(含创建人/修改人)
*/
public SystemConfig(String configKey, String configName, String configValue, Byte configType, Byte status,
String createdBy, String updatedBy) {
this.configKey = configKey;
this.configName = configName;
this.configValue = configValue;
this.configType = configType;
this.status = status;
this.createdBy = createdBy;
this.updatedBy = updatedBy;
this.deletedFlag = "N";
}
}
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.module.system.service;
import com.glsx.usedcar.module.system.dao.SystemConfigDao;
import com.glsx.usedcar.module.system.entity.SystemConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Optional;
/**
* 系统配置表(SystemConfig)业务层实现
*
* @since 2026-03-03
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemConfigService {
private final SystemConfigDao systemConfigDao;
/**
* 新增系统配置(自动校验配置键唯一性)
* @param systemConfig 配置对象
* @return 新增后的配置对象
*/
@Transactional(rollbackFor = Exception.class)
public SystemConfig addConfig(SystemConfig systemConfig) {
// 1. 核心参数校验
Assert.notNull(systemConfig, "系统配置对象不能为空");
Assert.hasText(systemConfig.getConfigKey(), "配置键不能为空");
Assert.hasText(systemConfig.getConfigName(), "配置名称不能为空");
Assert.notNull(systemConfig.getConfigType(), "配置类型不能为空");
Assert.notNull(systemConfig.getStatus(), "配置状态不能为空");
Assert.hasText(systemConfig.getCreatedBy(), "创建人不能为空");
Assert.hasText(systemConfig.getUpdatedBy(), "修改人不能为空");
// 2. 校验配置键唯一性(未删除的配置中不能重复)
SystemConfig existConfig = systemConfigDao.findByConfigKeyAndDeletedFlag(systemConfig.getConfigKey(), "N");
if (existConfig != null) {
throw new IllegalArgumentException("配置键[" + systemConfig.getConfigKey() + "]已存在,不能重复新增");
}
// 3. 填充默认值(保证字段完整性)
if (systemConfig.getDeletedFlag() == null) {
systemConfig.setDeletedFlag("N");
}
// 4. 保存配置并返回
SystemConfig savedConfig = systemConfigDao.save(systemConfig);
log.info("新增系统配置成功,配置键:{},ID:{}", savedConfig.getConfigKey(), savedConfig.getId());
return savedConfig;
}
/**
* 修改系统配置(校验配置键唯一性、仅修改非主键字段)
* @param systemConfig 配置对象(需包含id)
* @return 修改后的配置对象
*/
@Transactional(rollbackFor = Exception.class)
public SystemConfig updateConfig(SystemConfig systemConfig) {
// 1. 基础参数校验
Assert.notNull(systemConfig.getId(), "配置ID不能为空");
Assert.hasText(systemConfig.getUpdatedBy(), "修改人不能为空");
// 2. 查询原配置(必须存在且未删除)
SystemConfig oldConfig = systemConfigDao.findById(systemConfig.getId())
.orElseThrow(() -> new IllegalArgumentException("配置ID[" + systemConfig.getId() + "]不存在"));
if ("D".equals(oldConfig.getDeletedFlag())) {
throw new IllegalArgumentException("配置ID[" + systemConfig.getId() + "]已删除,不能修改");
}
// 3. 若修改配置键,需校验新键的唯一性
if (StringUtils.hasText(systemConfig.getConfigKey())
&& !oldConfig.getConfigKey().equals(systemConfig.getConfigKey())) {
SystemConfig existConfig = systemConfigDao.findByConfigKeyAndDeletedFlag(systemConfig.getConfigKey(), "N");
if (existConfig != null) {
throw new IllegalArgumentException("新配置键[" + systemConfig.getConfigKey() + "]已存在,不能修改");
}
oldConfig.setConfigKey(systemConfig.getConfigKey());
}
// 4. 覆盖可修改字段(保留创建时间/创建人,仅更新业务字段)
oldConfig.setConfigName(StringUtils.hasText(systemConfig.getConfigName())
? systemConfig.getConfigName() : oldConfig.getConfigName());
oldConfig.setConfigValue(StringUtils.hasText(systemConfig.getConfigValue())
? systemConfig.getConfigValue() : oldConfig.getConfigValue());
oldConfig.setConfigType(systemConfig.getConfigType() != null
? systemConfig.getConfigType() : oldConfig.getConfigType());
oldConfig.setStatus(systemConfig.getStatus() != null
? systemConfig.getStatus() : oldConfig.getStatus());
oldConfig.setUpdatedBy(systemConfig.getUpdatedBy());
// 5. 保存修改并返回
SystemConfig updatedConfig = systemConfigDao.save(oldConfig);
log.info("修改系统配置成功,配置ID:{},配置键:{}", updatedConfig.getId(), updatedConfig.getConfigKey());
return updatedConfig;
}
/**
* 逻辑删除系统配置(修改deleted_flag为D)
* @param id 配置主键ID
* @param operator 操作人
*/
@Transactional(rollbackFor = Exception.class)
public void deleteConfig(Integer id, String operator) {
// 1. 参数校验
Assert.notNull(id, "配置ID不能为空");
Assert.hasText(operator, "操作人不能为空");
// 2. 查询配置(不存在则抛异常)
SystemConfig config = systemConfigDao.findById(id)
.orElseThrow(() -> new IllegalArgumentException("配置ID[" + id + "]不存在"));
// 3. 已删除则无需重复操作
if ("D".equals(config.getDeletedFlag())) {
log.warn("配置ID[" + id + "]已删除,无需重复操作");
return;
}
// 4. 执行逻辑删除
config.setDeletedFlag("D");
config.setUpdatedBy(operator);
systemConfigDao.save(config);
log.info("逻辑删除系统配置成功,配置ID:{},配置键:{}", id, config.getConfigKey());
}
/**
* 根据配置键查询未删除的配置
* @param configKey 配置键
* @return 配置对象(空则返回Optional.empty())
*/
public Optional<SystemConfig> getConfigByKey(String configKey) {
if (!StringUtils.hasText(configKey)) {
return Optional.empty();
}
SystemConfig config = systemConfigDao.findByConfigKeyAndDeletedFlag(configKey, "N");
return Optional.ofNullable(config);
}
/**
* 根据状态查询未删除的配置列表
* @param status 状态(1:启用;2:禁用)
* @return 配置列表
*/
public List<SystemConfig> listConfigByStatus(Byte status) {
Assert.notNull(status, "配置状态不能为空");
return systemConfigDao.findByStatusAndDeletedFlag(status, "N");
}
/**
* 根据配置类型查询未删除的配置列表
* @param configType 配置类型(1:数值型;2:字符串型;3:布尔型;4:日期型;5:JSON型)
* @return 配置列表
*/
public List<SystemConfig> listConfigByType(Byte configType) {
Assert.notNull(configType, "配置类型不能为空");
return systemConfigDao.findByConfigTypeAndDeletedFlag(configType, "N");
}
/**
* 获取配置值(解析为整数,配置不存在/类型不匹配返回默认值)
* @param configKey 配置键
* @param defaultValue 默认值
* @return 解析后的整数值
*/
public Integer getConfigValueAsInt(String configKey, Integer defaultValue) {
Optional<SystemConfig> configOpt = getConfigByKey(configKey);
// 配置不存在/非数值型,返回默认值
if (configOpt.isEmpty() || !Byte.valueOf((byte)1).equals(configOpt.get().getConfigType())) {
return defaultValue;
}
try {
return Integer.parseInt(configOpt.get().getConfigValue());
} catch (NumberFormatException e) {
log.warn("配置键[{}]的值[{}]无法解析为整数,返回默认值[{}]",
configKey, configOpt.get().getConfigValue(), defaultValue);
return defaultValue;
}
}
/**
* 获取配置值(解析为布尔值,配置不存在/类型不匹配返回默认值)
* @param configKey 配置键
* @param defaultValue 默认值
* @return 解析后的布尔值
*/
public Boolean getConfigValueAsBoolean(String configKey, Boolean defaultValue) {
Optional<SystemConfig> configOpt = getConfigByKey(configKey);
// 配置不存在/非布尔型,返回默认值
if (configOpt.isEmpty() || !Byte.valueOf((byte)3).equals(configOpt.get().getConfigType())) {
return defaultValue;
}
String value = configOpt.get().getConfigValue();
if ("true".equalsIgnoreCase(value) || "1".equals(value)) {
return true;
} else if ("false".equalsIgnoreCase(value) || "0".equals(value)) {
return false;
} else {
log.warn("配置键[{}]的值[{}]无法解析为布尔值,返回默认值[{}]",
configKey, value, defaultValue);
return defaultValue;
}
}
/**
* 获取配置值(字符串类型,配置不存在返回默认值)
* @param configKey 配置键
* @param defaultValue 默认值
* @return 配置字符串值
*/
public String getConfigValueAsString(String configKey, String defaultValue) {
Optional<SystemConfig> configOpt = getConfigByKey(configKey);
if (configOpt.isEmpty()) {
return defaultValue;
}
return StringUtils.hasText(configOpt.get().getConfigValue())
? configOpt.get().getConfigValue() : defaultValue;
}
}
\ No newline at end of file \ No newline at end of file
...@@ -219,6 +219,24 @@ public class Vehicle extends AuditingEntity implements Serializable { ...@@ -219,6 +219,24 @@ public class Vehicle extends AuditingEntity implements Serializable {
private String appraisalRemark; private String appraisalRemark;
/** /**
* 系统自动加价开关 1 开启 0 关闭 默认关闭
*/
@Column
private Integer autoBidSwitch;
/**
* 加价幅度,单位 : 元
*/
@Column
private Double autoBidRange;
/**
* 加价触发时机, 在几秒触发,
*/
@Column
private Double autoBidTrigger;
/**
* 车辆图片列表 * 车辆图片列表
*/ */
@Convert(converter = CarImageListConverter.class) @Convert(converter = CarImageListConverter.class)
......
package com.glsx.usedcar.module.vehicle.entity.vo;
import lombok.*;
/**
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class VehicleAutoBidVO {
/**
* 车辆id
*/
private int vehicleId;
/**
* 系统自动加价开关 1 开启 0 关闭 默认关闭
*/
private Integer autoBidSwitch;
/**
* 加价幅度,单位 : 元
*/
private double autoBidRange;
/**
* 加价触发时机, 在几秒触发,
*/
private double autoBidTrigger;
}
...@@ -7,12 +7,14 @@ import com.glsx.usedcar.module.vehicle.domain.CarImage; ...@@ -7,12 +7,14 @@ import com.glsx.usedcar.module.vehicle.domain.CarImage;
import com.glsx.usedcar.module.vehicle.domain.VehicleHistoryProjection; import com.glsx.usedcar.module.vehicle.domain.VehicleHistoryProjection;
import com.glsx.usedcar.module.vehicle.domain.VehicleVenue; import com.glsx.usedcar.module.vehicle.domain.VehicleVenue;
import com.glsx.usedcar.module.vehicle.entity.*; import com.glsx.usedcar.module.vehicle.entity.*;
import com.glsx.usedcar.module.vehicle.entity.vo.VehicleAutoBidVO;
import com.glsx.usedcar.module.venue.dao.AreaDao; import com.glsx.usedcar.module.venue.dao.AreaDao;
import com.glsx.usedcar.module.venue.dao.VenueDao; import com.glsx.usedcar.module.venue.dao.VenueDao;
import com.glsx.usedcar.module.venue.dao.WarehousingDao; import com.glsx.usedcar.module.venue.dao.WarehousingDao;
import com.glsx.usedcar.module.venue.entity.Area; import com.glsx.usedcar.module.venue.entity.Area;
import com.glsx.usedcar.module.venue.entity.Venue; import com.glsx.usedcar.module.venue.entity.Venue;
import com.glsx.usedcar.module.venue.entity.Warehousing; import com.glsx.usedcar.module.venue.entity.Warehousing;
import com.glsx.usedcar.resp.BaseResp;
import com.glsx.usedcar.util.CoderGenerator; import com.glsx.usedcar.util.CoderGenerator;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.hibernate.ObjectNotFoundException; import org.hibernate.ObjectNotFoundException;
...@@ -320,4 +322,24 @@ public class VehicleService { ...@@ -320,4 +322,24 @@ public class VehicleService {
public long countByVehicleStateAndVenueId(int venueId) { public long countByVehicleStateAndVenueId(int venueId) {
return vehicleDao.countByVenue_VenueIdAndVehicleStateNotIn(venueId, List.of(Vehicle.VehicleState.COMPLETED, Vehicle.VehicleState.CANCELED)); return vehicleDao.countByVenue_VenueIdAndVehicleStateNotIn(venueId, List.of(Vehicle.VehicleState.COMPLETED, Vehicle.VehicleState.CANCELED));
} }
public BaseResp<Boolean> autoBid(VehicleAutoBidVO vehicleAutoBidVO) {
Optional<Vehicle> vehicleOptional = vehicleDao.findById(vehicleAutoBidVO.getVehicleId());
if (vehicleOptional.isEmpty()) {
return BaseResp.fail("车辆不存在.");
}
Vehicle vehicle = vehicleOptional.get();
if (!vehicle.getVehicleState().equals(Vehicle.VehicleState.PENDING_AUCTION)
&& !vehicle.getVehicleState().equals(Vehicle.VehicleState.WAIT_AUCTION)
&& !vehicle.getVehicleState().equals(Vehicle.VehicleState.PREVIEW)
&& !vehicle.getVehicleState().equals(Vehicle.VehicleState.AUCTIONING)
) {
return BaseResp.fail("车辆状态异常.");
}
vehicle.setAutoBidSwitch(vehicleAutoBidVO.getAutoBidSwitch());
vehicle.setAutoBidRange(vehicleAutoBidVO.getAutoBidRange());
vehicle.setAutoBidTrigger(vehicleAutoBidVO.getAutoBidTrigger());
vehicleDao.save(vehicle);
return BaseResp.success(true);
}
} }
\ No newline at end of file \ No newline at end of file
package com.glsx.usedcar.util;
import java.time.*;
public class LocalDateTimeUtil {
/**
* 毫秒级时间戳转LocalDateTime(使用系统默认时区)
* @param milliTimestamp 毫秒级时间戳(long类型)
* @return LocalDateTime
*/
public static LocalDateTime milliToLocalDateTime(long milliTimestamp) {
// 1. 毫秒时间戳转Instant(UTC时间)
Instant instant = Instant.ofEpochMilli(milliTimestamp);
// 2. 结合系统默认时区(如Asia/Shanghai)转ZonedDateTime,再转LocalDateTime
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
}
...@@ -18,7 +18,7 @@ public class AuctionSchedule { ...@@ -18,7 +18,7 @@ public class AuctionSchedule {
private AuctionService auctionService; private AuctionService auctionService;
@Scheduled(fixedDelay = 1000 * 10, initialDelay = 1000 * 20) @Scheduled(fixedDelay = 1000 * 1, initialDelay = 1000 * 20)
public void auctionTask() { public void auctionTask() {
try { try {
auctionService.autoAuctionedAuctions(); auctionService.autoAuctionedAuctions();
......
package com.glsx.usedcar.task;
import com.glsx.usedcar.module.auction.service.AuctionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
*
*/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LightPoollingAuctionSchedule {
private final AuctionService auctionService;
/**
* 自动竞价定时任务
* 500毫秒更新一次
*/
@Scheduled(fixedDelay = 500, initialDelay = 1000 * 5)
public void autoBidding() {
// log.info("自动竞价定时任务");
long start = System.currentTimeMillis();
try {
auctionService.autoBidding();
} catch (Exception e) {
log.error("自动竞价定时任务异常", e);
} finally {
// long end = System.currentTimeMillis();
// log.info("自动竞价定时任务耗时{}ms", end - start);
}
}
/**
* 明拍竞价中模式为轮询出价的车辆更新为拍卖中
*/
@Scheduled(fixedDelay = 5000, initialDelay = 1000 * 5)
public void autoBiddingLightPoollingAuctions() {
long start = System.currentTimeMillis();
try {
auctionService.autoBiddingLightPoollingAuctions();
} catch (Exception e) {
log.error("自动更新明拍竞价中模式为轮询出价的车辆更新为拍卖中出现异常", e);
} finally {
// long end = System.currentTimeMillis();
// log.info("自动更新明拍竞价中模式为轮询出价的车辆更新为拍卖中耗时{}ms", end - start);
}
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!