awesomemax
@awesomemax
java developer

Что делать если данные не десериализуются?

Всем привет, решил изучить редис в качестве кэша для своего мини приложения и столкнулся с проблемой десериализации данных, я навесил на метод который возвращает ответ в ResponseEntity аннотацию @Cacheable, я знаю что ResponseEntity не является сериализуемой как требует редис, поэтому я сделал свой Entity с интерфейсом Serializable, и почему то редис не может обратно десериализовать данные.
Сам класс где есть аннотация @Cacheable:
@Slf4j
@RestController
@RequestMapping("/link")
public class LinkController implements Serializable {
    private static final Logger LOGGER = LoggerFactory.getLogger(LinkController.class);
    @Serial
    private static final long serialVersionUID = -7917644949275952078L;
    @Autowired
    private UserLinkRepository userLinkRepository;
    @Autowired
    private LinkService linkService;

    @GetMapping("/all")
    public CustomResponseEntity<?> allUsers() {
        List<UserLink> allUsers = userLinkRepository.findAll();
        LOGGER.info("Received GET request '/all'");
        return new CustomResponseEntity<>(allUsers, HttpStatus.FOUND);
    }

    @GetMapping("/user-{id}")
    @Cacheable(cacheNames = "userById")
    public CustomResponseEntity<?> getUserById(@PathVariable(name = "id") Long id) {
        LOGGER.info("Received GET request '/user-{}'",id);
        return new CustomResponseEntity<>(userLinkRepository.findById(id), HttpStatus.FOUND);
    }

    @PostMapping("/create-short-link")
    @Cacheable(cacheNames = "shortLinks")
    public CustomResponseEntity<?> getShortLink(@RequestBody UserLink user) {
        String shortLink = linkService.createCutLink(user.getLongLink());
        user.setShortLink(shortLink);
        userLinkRepository.save(user);
        LOGGER.info("Received POST request '/create-short-link'");
        return new CustomResponseEntity<>(shortLink,HttpStatus.CREATED);
    }
    @GetMapping("/{shortLink}")
    public CustomResponseEntity<?> redirect(@PathVariable("shortLink") String shortLink) {
        var url = linkService.getOriginalLink(shortLink);
        LOGGER.info("Received GET request "+ "/" +shortLink);
        return (CustomResponseEntity<?>) ResponseEntity.status(HttpStatus.FOUND)
                .location(URI.create(url))
                .build();
    }
}


Кастомный Entity:
public class CustomResponseEntity<T> extends ResponseEntity implements Serializable {

    @Serial
    private static final long serialVersionUID = -950111661934555731L;

    public CustomResponseEntity(HttpStatusCode status) {
        super(status);
    }

    public CustomResponseEntity(Object body, HttpStatusCode status) {
        super(body, status);
    }

    public CustomResponseEntity(MultiValueMap headers, HttpStatusCode status) {
        super(headers, status);
    }

    public CustomResponseEntity(Object body, MultiValueMap headers, HttpStatusCode status) {
        super(body, headers, status);
    }

    public CustomResponseEntity(Object body, MultiValueMap headers, int rawStatus) {
        super(body, headers, rawStatus);
    }
}


Я не понимаю куда навешивать эти аннотации в сервис или в контроллер, в любом случае нужно понять почему появляется данная ошибка:

ERROR 94627 --- [nio-8083-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Cannot construct instance of `com.springrest.linkcut.HelperClass.CustomResponseEntity` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"{"@class":"com.springrest.linkcut.HelperClass.CustomResponseEntity","headers":{"@class":"org.springframework.http.ReadOnlyHttpHeaders"},"body":{"@class":"java.util.Optional","empty":false,"present":true},"statusCodeValue":302,"statusCode":["org.springframework.http.HttpStatus","FOUND"]}"; line: 1, column: 69]] with root cause

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.springrest.linkcut.HelperClass.CustomResponseEntity` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (byte[])"{"@class":"com.springrest.linkcut.HelperClass.CustomResponseEntity","headers":{"@class":"org.springframework.http.ReadOnlyHttpHeaders"},"body":{"@class":"java.util.Optional","empty":false,"present":true},"statusCodeValue":302,"statusCode":["org.springframework.http.HttpStatus","FOUND"]}"; line: 1, column: 69]
  • Вопрос задан
  • 217 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы