Home  >  Article  >  Database  >  How does Springboot integrate redis to achieve simple data writing and reading?

How does Springboot integrate redis to achieve simple data writing and reading?

PHPz
PHPzforward
2023-06-02 17:25:241398browse

引入maven依赖:
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>${redission}</version>
</dependency>



redisUtil.java
package com.gllic.workweixin.utils;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

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

@Component
public class RedisUtil {
    @Resource
    private RedissonClient redissonClient;

    public boolean setString(String key, Object value, long time) {
        try {
            RBucket rBucket = redissonClient.getBucket(key);
            if (time > 0) {
               rBucket.set(value,time,TimeUnit.SECONDS);
            } else {
                rBucket.set(value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String getString(String key) {
        if(key==null)
            return null;
        RBucket rBucket=redissonClient.getBucket(key);
        Object o = rBucket.get();
        return o == null ? null : o.toString();
    }

//    public boolean setString(String key, Object value, long time) {
//        try {
//            if (time > 0) {
//                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
//            } else {
//                redisTemplate.opsForValue().set(key, value);
//            }
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }
//
//    public String getString(String key) {
//        if(key==null)
//            return null;
//        Object o = redisTemplate.opsForValue().get(key);
//        return o == null ? null : o.toString();
//    }

}

写入:
RedisUtil.setString("key","value",time);
读取:
RedisUtil.getString("key");

The above is the detailed content of How does Springboot integrate redis to achieve simple data writing and reading?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete