SpringBoot(四)SpringBoot整合Redis

SpringBoot(四)SpringBoot整合Redis

<!-- redis依赖包 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
#配置连接Redis
#主机地址
spring.redis.host=IP
#端口号
spring.redis.port=6379
#连接的超时时间
spring.redis.timeout=3000
#redis连接池
#连接池最大连接数
spring.redis.jedis.pool.max-active=8
#最大阻塞等待时间
spring.redis.jedis.pool.max-wait=3000
#最大空闲连接数
spring.redis.jedis.pool.max-idle=8
#最小空闲连接数
spring.redis.jedis.pool.min-idle=2
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     */
    public boolean set( String key, Object value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public boolean getAndSet(final String key, String value) {
        boolean result = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public boolean delete(final String key) {
        boolean result = false;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
public class Article implements Serializable {
    private Integer id;
    private String title;
    private String content;
}
@RunWith(SpringRunner.class)
@SpringBootTest
class BootmybatisApplicationTests {
    
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisUtils redisUtils;

    //写入,key :1 ,value :MySQL数据库中id为1的article记录
    @Test
    void insertRedis(){
        redisUtils.set("1",articleMapper.selectArticle(1));
        System.out.println("success");
    }
    
    @Test
    void selectRedis(){
        Article article = (Article) redisUtils.get("1");
        System.out.println(article);
    }

}

切记:使用Java程序向Redis写入对象时,记得对对象实体类进行序列化

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值