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<Country> 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<Country> 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<Country> getChildren() {
        return children;
    }

    public void setChildren(List<Country> 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();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值