spring boot中redis的使用

1. 添加Redis依赖

首先,需要在pom.xml文件中添加Redis依赖:

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

这个依赖包含了Spring Data Redis,以及Jedis和Lettuce这两种Redis客户端的实现。

2. 配置Redis连接

在SpringBoot项目中,可以通过在application.propertiesapplication.yml文件中配置Redis连接信息。以下是一个示例:

spring:
  redis:
    host: localhost
    port: 6379
    password: mypassword
    timeout: 3000
    database: 0

其中,hostport分别是Redis服务器的地址和端口号,password是Redis的密码(如果没有密码,可以不填),timeout是Redis连接超时时间,jedis.pool是连接池的相关设置。

3. 创建RedisTemplate

使用Spring Data Redis操作Redis,通常会使用RedisTemplate类。为了方便起见,我们可以创建一个工具类来管理RedisTemplate的创建和使用。以下是一个示例:

package com.redisTest.system.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author luft-mensch
 */
@Component
public class RedisUtils {

    /**
     * 如果使用 @Autowired 注解完成自动装配 那么
     * RedisTemplate要么不指定泛型,要么泛型 为<Stirng,String> 或者<Object,Object>
     * 如果你使用其他类型的 比如RedisTemplate<String,Object>
     * 那么请使用 @Resource 注解
     * */
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 缓存value
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean cacheValue(String key, Object value, long time) {
        try {
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value);
            if (time > 0) {
                // 如果有设置超时时间的话
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Throwable e) {
            logger.error("缓存[" + key + "]失败, value[" + value + "] " + e.getMessage());
        }
        return false;
    }

    /**
     * 缓存value,没有设置超时时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean cacheValue(String key, Object value) {
        return cacheValue(key, value, -1);
    }

    /**
     * 判断缓存是否存在
     *
     * @param key
     * @return
     */
    public boolean containsKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Throwable e) {
            logger.error("判断缓存是否存在时失败key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return false;
    }

    /**
     * 根据key,获取缓存
     *
     * @param key
     * @return
     */
    public Object getValue(String key) {
        try {
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            return valueOperations.get(key);
        } catch (Throwable e) {
            logger.error("获取缓存时失败key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return null;
    }

    /**
     * 移除缓存
     *
     * @param key
     * @return
     */
    public boolean removeValue(String key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Throwable e) {
            logger.error("移除缓存时失败key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return false;
    }

    /**
     * 根据前缀移除所有以传入前缀开头的key-value
     *
     * @param pattern
     * @return
     */
    public boolean removeKeys(String pattern) {
        try {
            Set<String> keySet = redisTemplate.keys(pattern + "*");
            redisTemplate.delete(keySet);
            return true;
        } catch (Throwable e) {
            logger.error("移除key[" + pattern + "]前缀的缓存时失败", "err[" + e.getMessage() + "]");
        }
        return false;
    }

}

在这个示例中,我们使用@Resource注解自动注入了一个RedisTemplate<String, Object>对象。然后,我们提供了三个方法来对Redis进行操作:cacheValue方法用于缓存数据,getValue方法用于获取缓存数据,removeValue方法用于删除缓存数据。这些方法都是通过redisTemplate对象来实现的。

需要注意的是,在使用RedisTemplate时,需要指定键值对的类型。在这个示例中,我们指定了键的类型为String,值的类型为Object

注意:

 * 如果使用 @Autowired 注解完成自动装配 

 * 那么 RedisTemplate要么不指定泛型,要么泛型 为<Stirng,String> 或者<Object,Object>

 * 如果你使用其他类型的 比如RedisTemplate<String,Object>

 * 那么请使用 @Resource 注解,否则会报以下错误:RedisTemplate 注入失败

Description:

Field redisTemplate in com.redisTest.system.utils.RedisUtils required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.

进程已结束,退出代码1

4. 使用RedisTemplate

在上面的示例中,我们已经创建了一个RedisTemplate对象,并提供了一些方法来对Redis进行操作。现在,我们可以在SpringBoot项目中的任何地方使用这个工具类来进行缓存操作。以下是一个示例

@RestController
public class UserController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

  	@GetMapping("/users/{id}")
  	public User getUserById(@PathVariable Long id) {
  
    	  String key = "user_" + id;
    	  User user = (User) redisUtils.getValue(key);  
    	  if (user == null) {  
     	      user = userService.getUserById(id);  
    	      redisUtils.cacheValue(key, user);  
   	   }  
  	    return user;  
	  }
}

在这个示例中,我们创建了一个UserController类,用于处理HTTP请求。在getUserById方法中,我们首先构造了一个缓存的key,然后使用redisUtils.getValue方法从Redis中获取缓存数据。如果缓存中没有数据,我们调用userService.getUserById方法从数据库中获取数据,并使用redisUtils.cacheValue方法将数据存入Redis缓存中。最后,返回获取到的数据。

通过这个示例,我们可以看到,在SpringBoot项目中使用Redis作为缓存的流程。我们首先需要添加Redis依赖,然后在配置文件中配置Redis连接信息。接着,我们创建了一个RedisUtils工具类来管理RedisTemplate的创建和使用。最后,我们在控制器中使用RedisUtils来对Redis进行缓存操作。

5. 乱码解决

Redis 使用过程中可能会遇到 key 和 value 乱码的现象存在,具体解决方法见:

  • 9
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
使用Spring Boot集成Redis非常简单,只需要遵循以下步骤: 1. 在`pom.xml`文件添加`spring-boot-starter-data-redis`依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在`application.properties`文件配置Redis连接信息: ``` spring.redis.host=localhost spring.redis.port=6379 ``` 3. 创建一个RedisTemplate bean: ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } ``` 在这个示例,我们使用了`StringRedisSerializer`用于序列化键,`GenericJackson2JsonRedisSerializer`用于序列化值。 4. 在需要使用Redis的地方注入RedisTemplate bean: ``` @RestController public class MyController { @Autowired private RedisTemplate<String, Object> redisTemplate; @GetMapping("/redis") public String redis() { redisTemplate.opsForValue().set("myKey", "myValue"); Object value = redisTemplate.opsForValue().get("myKey"); return value.toString(); } } ``` 这个示例我们注入了RedisTemplate bean,然后使用`opsForValue()`方法获取操作字符串的Redis操作对象,并且执行了设置和获取操作。 以上就是使用Spring Boot集成Redis的步骤,希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要成为大V的小v

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值