package com.izouma.nineth.web; import com.izouma.nineth.enums.OperationType; import com.izouma.nineth.exception.BusinessException; import com.izouma.nineth.service.CacheService; import com.izouma.nineth.service.CollectionService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; @RestController @RequestMapping("/cache") @AllArgsConstructor @Slf4j public class CacheController { private final CacheService cacheService; private final CollectionService collectionService; @RequestMapping("/clear") @PreAuthorize("hasRole('ADMIN')") public void clear(String name, String stringParam, Long longParam) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Method method; if (StringUtils.isNotEmpty(stringParam)) { method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name)), String.class); method.invoke(cacheService, stringParam); } else if (longParam != null) { method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name)), Long.class); method.invoke(cacheService, longParam); } else { method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name))); method.invoke(cacheService); } } @PostMapping(value = "/operating/{collectionId}/{num}/{operationType}") public void operatingStockOrSale(@PathVariable Long collectionId, @PathVariable int num, @PathVariable OperationType operationType) { if (Objects.isNull(collectionId)) { throw new BusinessException("collectionId参数错误"); } if (0 >= num) { throw new BusinessException("num参数错误"); } if (Objects.isNull(operationType)) { throw new BusinessException("操作类型不可为空"); } switch (operationType) { case INCREASE_STOCK: log.info(String.format("collectionId:[%S] 加库存:[%S]", collectionId, num)); collectionService.increaseStock(collectionId, num); break; case DECREASE_STOCK: log.info(String.format("collectionId:[%S] 减库存:[%S]", collectionId, num)); collectionService.decreaseStock(collectionId, num); break; case INCREASE_SALE: log.info(String.format("collectionId:[%S] 加销量:[%S]", collectionId, num)); collectionService.increaseSale(collectionId, num); break; case DECREASE_SALE: log.info(String.format("collectionId:[%S] 减销量:[%S]", collectionId, num)); collectionService.decreaseSale(collectionId, num); break; default: String err = String.format("暂不支持的操作类型:[%S]", operationType); log.info(err); throw new BusinessException(err); } } }