栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Jedis操作Redis数据库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Jedis操作Redis数据库

Jedis的方法基本和Redis的指令一一对应。

把一个对象写入Redis:

package com.qiuqiu.jedis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        try (Jedis jedis = new Jedis("123.57.61.22", 6379)) {
            jedis.select(0);

            Country china = new Country("china", "beijing", 960);
            Country jiangSu = new Country("jiangsu", "nanjing", 40);
            List list = new ArrayList<>();
            list.add(jiangSu);
            china.setChildren(list);

            String str = JSONObject.toJSONString(china);
            System.out.println(str);

            jedis.set("country#001", str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class Country {
    private String name;
    private String capital;
    private int size;
    List children;

    public Country(String name, String capital, int size) {
        this.name = name;
        this.capital = capital;
        this.size = size;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public List getChildren() {
        return children;
    }

    public void setChildren(List children) {
        this.children = children;
    }
}

从Redis中读取一个对象:

public class Test {
    public static void main(String[] args) {
        try (Jedis jedis = new Jedis("123.57.61.22", 6379)) {
            jedis.select(0);

            String str = jedis.get("country#001");

            Country country = JSONObject.parseObject(str, Country.class);
            System.out.println(country);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1031734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号