spring怎么配置redis缓存

不及物动词 其他 47

回复

共3条回复 我来回复
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    配置Spring中的Redis缓存需要进行以下步骤:

    步骤一:添加Redis依赖
    首先,需要在项目的依赖中添加Redis相关的依赖。我们可以使用Spring Boot提供的starter依赖简化配置,通过在pom.xml文件中添加以下依赖:

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

    步骤二:配置Redis连接信息
    在Spring Boot的配置文件(application.properties或application.yml)中配置Redis连接信息,包括主机名、端口、密码等。示例配置如下:

    spring.redis.host=localhost
    spring.redis.port=6379
    spring.redis.password=yourpassword
    

    步骤三:配置RedisTemplate
    在Spring Boot中,可以使用RedisTemplate来进行Redis的操作。在配置类中添加以下配置:

    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
        
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
            return template;
        }
    }
    

    步骤四:配置缓存注解
    使用Redis做缓存时,我们可以使用Spring提供的缓存注解来简化缓存的使用。在需要缓存的方法上添加@Cacheable@CachePut@CacheEvict注解。示例代码如下:

    @Service
    public class UserService {
        
        @Autowired
        private UserRepository userRepository;
        
        @Cacheable(value = "users", key = "#id")
        public User getUserById(Long id) {
            return userRepository.findById(id);
        }
        
        @CachePut(value = "users", key = "#user.id")
        public User saveUser(User user) {
            return userRepository.save(user);
        }
        
        @CacheEvict(value = "users", key = "#id")
        public void deleteUserById(Long id) {
            userRepository.deleteById(id);
        }
    }
    

    以上就是配置Spring中的Redis缓存的步骤,通过这些配置,我们可以在Spring项目中方便地使用Redis作为缓存存储。

    1年前 0条评论
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    在Spring框架中配置Redis缓存有以下几个步骤:

    1. 引入相关依赖:首先需要在项目的pom.xml文件中引入Spring对Redis的支持依赖,如下所示:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    1. 配置Redis连接:接下来需要在项目的配置文件中配置Redis连接信息,包括Redis服务器的地址、端口、密码等。你可以在application.properties或application.yml文件中进行配置,示例如下:
    spring.redis.host=127.0.0.1
    spring.redis.port=6379
    spring.redis.password=your_password
    
    1. 创建RedisTemplate Bean:接下来需要创建一个RedisTemplate Bean,用于执行与Redis服务器的交互操作。通常情况下,你可以通过配置RedisConnectionFactory来创建RedisTemplate Bean,如下所示:
    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            return redisTemplate;
        }
    
    }
    

    注意,这里将字符串键和JSON对象值的序列化器设置为StringRedisSerializer和GenericJackson2JsonRedisSerializer,你可以根据实际需要进行调整。

    1. 配置缓存注解支持:接下来需要在启动类中添加@EnableCaching注解,以启用Spring的缓存注解支持,如下所示:
    @SpringBootApplication
    @EnableCaching
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    
    1. 使用缓存注解:现在你可以在你的Service或Repository组件上使用缓存注解来定义缓存操作。常用的缓存注解包括@Cacheable、@CachePut、@CacheEvict等,你可以根据需要选择适合的注解进行使用。
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        @Cacheable(value = "users", key = "#id")
        public User getUserById(Long id) {
            return userRepository.findById(id).orElse(null);
        }
    
        @Override
        @CachePut(value = "users", key = "#user.id")
        public User saveUser(User user) {
            return userRepository.save(user);
        }
    
        @Override
        @CacheEvict(value = "users", key = "#id")
        public void deleteUserById(Long id) {
            userRepository.deleteById(id);
        }
    
    }
    

    上述代码示例中,@Cacheable注解表示方法的结果会被缓存,@CachePut注解表示方法的结果会被更新到缓存中,@CacheEvict注解表示方法的结果会从缓存中清除。

    通过以上步骤,你就可以在Spring框架中成功配置和使用Redis缓存了。

    1年前 0条评论
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    在Spring框架中,可以使用Redis作为缓存来提高系统的性能和响应速度。下面是一种常用的配置Redis缓存的方法和操作流程。

    1. 添加Redis依赖库
      首先,需要在项目的构建文件中添加Redis的依赖库。可以在Maven项目中,在pom.xml文件中添加以下依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    1. 配置Redis连接
      在Spring Boot项目中,可以在application.properties或application.yml文件中配置Redis的连接信息。以下是一个示例的配置信息:
    spring:
      redis:
        host: localhost
        port: 6379
    

    其中,spring.redis.host指定Redis的主机地址,spring.redis.port指定Redis的端口号。

    1. 创建RedisTemplate对象
      在Spring框架中,可以使用RedisTemplate来操作Redis。需要创建一个RedisTemplate对象,并进行配置。可以通过注解@Bean来创建RedisTemplate对象,并使用@Configuration注解指明这是一个配置类。
    @Configuration
    public class RedisConfig {
        
        @Value("${spring.redis.host}")
        private String host;
        
        @Value("${spring.redis.port}")
        private int port;
        
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory());
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new JdkSerializationRedisSerializer());
            return template;
        }
        
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(host);
            config.setPort(port);
            return new JedisConnectionFactory(config);
        }
    }
    

    在上面的代码中,redisTemplate()方法用于创建RedisTemplate对象,redisConnectionFactory()方法用于创建Redis连接工厂。

    1. 使用缓存注解
      在需要使用Redis缓存的方法上,可以使用Spring提供的缓存注解来实现缓存的操作。常用的缓存注解有@Cacheable@CachePut@CacheEvict
    • @Cacheable:用于查询方法,先从缓存中查找数据,如果找到则直接返回,如果没有找到则执行方法,并将返回结果存入缓存中。可以指定缓存的key和缓存的条件。
    • @CachePut:用于更新方法,每次都会执行方法,并将返回结果存入缓存中。
    • @CacheEvict:用于删除方法,执行方法后会将缓存中的数据删除。

    可以在类或方法上使用缓存注解,示例如下:

    @RestController
    public class UserController {
        
        @Autowired
        private UserService userService;
        
        @GetMapping("/users/{id}")
        @Cacheable(value = "userCache", key = "#id")
        public User getUserById(@PathVariable("id") Long id) {
            return userService.getUserById(id);
        }
        
        @PostMapping("/users")
        @CachePut(value = "userCache", key = "#user.id")
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }
        
        @DeleteMapping("/users/{id}")
        @CacheEvict(value = "userCache", key = "#id")
        public void deleteUserById(@PathVariable("id") Long id) {
            userService.deleteUserById(id);
        }
    }
    

    在上面的代码中,getUserById()方法会先从缓存中查找用户数据,如果找到则直接返回,否则执行userService.getUserById(id)方法,并将返回结果存入缓存中。

    1. 配置缓存管理器
      为了管理缓存,可以配置一个缓存管理器。可以通过注解@Bean来创建缓存管理器,并使用@Configuration注解指明这是一个配置类。
    @Configuration
    @EnableCaching
    public class CacheConfig extends CachingConfigurerSupport {
        
        @Bean
        @Override
        public CacheManager cacheManager() {
            RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(1)); // 设置缓存过期时间为1分钟
            return RedisCacheManager.builder(redisConnectionFactory())
                    .cacheDefaults(cacheConfig)
                    .build();
        }
        
        @Bean
        public RedisCacheManager redisCacheManager() {
            RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory());
            RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(1)); // 设置缓存过期时间为1分钟
            return new RedisCacheManager(redisCacheWriter, cacheConfiguration);
        }
        
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(host);
            config.setPort(port);
            return new JedisConnectionFactory(config);
        }
    }
    

    在上面的代码中,cacheManager()方法用于创建缓存管理器,redisCacheManager()方法用于创建Redis缓存管理器。可以通过cacheConfig.entryTtl()方法设置缓存的过期时间。

    以上就是一种配置Redis缓存的方法和操作流程。通过配置Redis连接和创建RedisTemplate对象,可以使用Redis作为缓存,提高系统的性能和响应速度。同时,使用缓存注解和配置缓存管理器,可以方便地管理缓存数据。

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部