Home > Database > Redis > body text

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

PHPz
Release: 2023-06-02 17:25:24
forward
1385 people have browsed it

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



redisUtil.java
Copy after login
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");
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template