Аннотация @TimeToLive не работает в проекте mu Spring Boot - PullRequest
0 голосов
/ 07 августа 2020

Я создал рабочую программу CRUD при загрузке Spring. Используя Redis, операция CRUD работает нормально. После этого я пробовал использовать функцию «время жить (ttl)», где, если я сохраню некоторые данные, он должен получить удаляется через 10 секунд, эта часть не работает ... Я пробовал использовать аннотацию @TimeToLive, но записи все еще присутствуют по истечении времени. Это мой main () -


import com.vishruth.cache.ArtifactSpringRedisExample.model.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class ArtifactSpringRedisExampleApplication extends JCacheConfigurerSupport {

    @Bean
    JedisConnectionFactory jedisConnectionFactory(){
        return new JedisConnectionFactory();
    }


    //plugging the factory to the redis template
    @Bean
    RedisTemplate<String, User> redisTemplate(){
        RedisTemplate<String, User> redisTemplate =new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }


//  @Bean
//  RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
//      return (builder) -> {
//          Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
//          configurationMap.put("cache1", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(20)));
//          configurationMap.put("cache2", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(2)));
//          builder.withInitialCacheConfigurations(configurationMap);
//      };
//  }


    public static void main(String[] args) {
        SpringApplication.run(ArtifactSpringRedisExampleApplication.class, args);
    }

}

Это мой UserRepositoryImpl-


import org.redisson.api.RMapCache;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Repository
public class UserRepositoryImpl implements UserRepository {

    private RedisTemplate<String,User> redisTemplate;
    private HashOperations hashOperations;

    public UserRepositoryImpl(RedisTemplate<String, User> redisTemplate) {
        this.redisTemplate = redisTemplate;
        hashOperations=redisTemplate.opsForHash();
    }

    @Override
//    @Cacheable( cacheManager ="cache1")
    public void save(User user) {

        hashOperations.put("USER",user.getId(),user);

    }

    @Override
    public Map<String,User> findAll() {
        return hashOperations.entries("USER");
    }

    @Override
    public User findById(String id) {
        return (User) hashOperations.get("USER",id);
    }

    @Override
    public void update(User user) {
        save(user);
    }

    @Override
    public void delete(String id) {

        hashOperations.delete("USER",id);

    }
}

Это мой интерфейс UserRepositoty -

package com.vishruth.cache.ArtifactSpringRedisExample.model;

import java.util.List;
import java.util.Map;

public interface UserRepository {

    void save(User user);
    Map<String,User> findAll();
    User findById(String id);
    void update(User user);
    void delete(String id);
}

Это мой класс пользователя -

package com.vishruth.cache.ArtifactSpringRedisExample.model;

import lombok.Data;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.TimeToLive;

import java.io.Serializable;

@RedisHash(timeToLive=10L)
@Data
public class User implements Serializable {

//    private static final long serialVersionUID = 6529685098267757690L;

    private String id;
    private String name;
    private Long salary;
    private Long ttl;


    public User(String id, String name, Long salary, Long ttl) {
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.ttl = ttl;
    }
}

Это мой класс конечной точки контроллера-

package com.vishruth.cache.ArtifactSpringRedisExample;


import com.vishruth.cache.ArtifactSpringRedisExample.model.User;
import com.vishruth.cache.ArtifactSpringRedisExample.model.UserRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/rest/user")
public class UserResource {

    public UserResource(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    private UserRepository userRepository;

    @GetMapping("/add/{id}/{name}")
    public User add(@PathVariable("id") final String id,@PathVariable("name") final String name){
        userRepository.save(new User(id,name,20000L,1L));
        return userRepository.findById(id);
    }

    @GetMapping("/update/{id}/{name}")
    public User update(@PathVariable("id") final String id,@PathVariable("name") final String name){
        userRepository.update(new User(id,name,20000L,1L));
        return userRepository.findById(id);
    }

    @GetMapping("/all")
    public Map<String,User> update(){
        return userRepository.findAll();
    }


    @GetMapping("/deleteById/{id}")
    public  User delete(@PathVariable("id") final String id){
        userRepository.delete(id);
        return userRepository.findById(id);

    }



}

Это мой файл pom-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.vishruth.cache</groupId>
    <artifactId>Artifact-Spring-Redis-Example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Artifact-Spring-Redis-Example</name>
    <description>Redis crud operation</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>


        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>



<!--        <dependency>-->
<!--            <groupId>com.google.guava</groupId>-->
<!--            <artifactId>guava</artifactId>-->
<!--            <version>18.0</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>org.springframework</groupId>-->
<!--            <artifactId>spring-context-support</artifactId>-->
<!--            <version>4.1.7.RELEASE</version>-->
<!--        </dependency>-->

        <!-- https://mvnrepository.com/artifact/org.redisson/redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.13.3</version>
        </dependency>





        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Почему нет @ RedisHa sh (Timetolive = 10L) не работает? Я новичок в Spring Boot и Redis, любая помощь приветствуется, заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...