Redis从基础命令到实战之字符串类型

字符串类型是Redis中最基本的数据类型,能存储任何形式的字符串和和二进制数据。本文以代码形式列举常用的操作命令,并在实践部分演示一个简单的商品管理功能,实现了通常使用关系型数据库开发的增改查功能,注意并没有实现删除功能,这将放在后面的列表类型中去实现。

一、常用命令

pom.xml

	<dependencies>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.8.1</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
	</dependencies>
StringExample.java

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.Jedis;

public class StringExample {

	public static void main(String[] args) {
		Jedis jedis = JedisProvider.getJedis();
		//清空数据库
		jedis.flushDB();

		String key = "redis_str";
		//判断key是否存在
		boolean exists = jedis.exists(key);
		if (exists) {
			//删除key,返回实际删除的行数
			long l = jedis.del(key);
			print("del " + key + "=" + l);
		}
		//新增key,成功返回 OK
		String result = jedis.set(key, "a string value");
		print("set " + key + "=" + result);
		//读取value长度
		print("strlen(" + key + ")=" + jedis.strlen(key));
		//读取value
		String value = jedis.get(key);
		print("get " + key + "=" + value);

		//设置过期时间为5秒
		jedis.expire(key, 5);
		//查看某个key的剩余生存时间,单位秒,永久生存或者不存在的都返回-1
		Long ttl = jedis.ttl(key);
		print("ttl of " + key + "=" + ttl);
		//移除某个key的生存时间
		jedis.persist(key);
		print("移除生存时间后 ttl of " + key + "=" + jedis.ttl(key));
		//查看key所储存的值的类型
		String type = jedis.type(key);
		print("type of " + key + "=" + type);

		//一次性新增多个key
		jedis.mset("key001", "value001", "key002", "value002", "key003",
				"value003", "key004", "value004");
		print("批量设置key: key001,key002,key003,key004");
		
		//读取所有key,遍历,判断类型
		System.out.println("读取所有key并筛选string类型");
		Set<String> keys = jedis.keys("*");
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			key = it.next();
			if (jedis.type(key).equals("string"))
				System.out.println("get " + key + "=" + jedis.get(key));
		}
		System.out.println("------------------------------------------------------");
		System.out.println();
		
		//一次性获取多个key值
		System.out.println("批量读取key: key001,key002,key003,key004");
		List<String> list = jedis.mget("key001", "key002", "key003", "key004");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
		System.out.println("------------------------------------------------------");
		System.out.println();
		//一次性删除多个key,返回成功删除个数
		Long del = jedis.del(new String[] { "key001", "key002" });
		print("[批量删除]del key001,key002=" + del);

		// 禁止覆盖
		Long setnx = jedis.setnx("key003", "value003_new");
		print("[禁止覆盖]setnx key003 to value003_new=" + setnx + "; value=" + jedis.get("key003"));

		//新增key同时设置有效期(秒)
		result = jedis.setex(key, 3, "setex demo");
		print("setex " + key + "(ttl 3)=" + result + "; value=" + jedis.get(key) + "; ttl=" + jedis.ttl(key));
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
		}
		print("[4秒之后]get " + key + "=" + jedis.get(key));
		
		//获取原值, 更新为新值一步完成
		key = "key003";
		String former = jedis.getSet(key, "value002-after-getset");
		print("getSet 原值:" + former + "; 新值" + jedis.get(key));

		//incr 自增
		key = "redis_num";
		jedis.del(key);
		long incr = jedis.incr(key);
		print("incr " + key + " = " + incr);
		incr = jedis.incr(key);
		print("incr " + key + " = " + incr);
		incr = jedis.incrBy(key, 100);
		print("incrBy " + key + " 100 = " + incr);
		Long decr = jedis.decrBy(key, 100);
		print("decrBy " + key + " 100 = " + decr);

		jedis.close();
	}

	private static void print(String info) {
		System.out.println(info);
		System.out.println("------------------------------------------------------");
		System.out.println();
	}
}
JedisProvider.java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisProvider {

	private static JedisPool pool;
	
	public static Jedis getJedis() {
		if(pool == null) {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(1024);
			config.setMaxIdle(200);
			config.setMaxWaitMillis(1000);
			config.setTestOnBorrow(true);
			config.setTestOnReturn(true);
			pool = new JedisPool(config, "127.0.0.1", 6380);
		}
		return pool.getResource();
	}
}

二、实践练习

StringLession.java

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;

import redis.clients.jedis.Jedis;

public class StringLession {

	public static void main(String[] args) {
		StringLession sl = new StringLession();
		sl.clear();
		
		//添加一批商品
		for(int i = 0; i< 41; i++) {
			Goods goods = new Goods(0, "goods" + String.format("%05d", i), i);
			sl.addGoods(goods);
		}
		//读取商品总数
		System.out.println("商品总数: " + sl.getTotalCount());
		//分页显示
		List<Goods> list = sl.getGoodsList(2, 20);
		System.out.println("第二页商品:");
		for(Goods goods : list) {
			System.out.println(goods);
		}
	}
	
	private Jedis jedis = null;
	
	public StringLession() {
		this.jedis = JedisProvider.getJedis();
	}

	/**
	 * 获得一个自增主键值
	 * @return
	 */
	private long getIncrementId() {
		String key = "goods:count";
		return jedis.incr(key);
	}
	
	/**
	 * 添加一个商品
	 * @param goods
	 * @return
	 */
	public boolean addGoods(Goods goods) {
		long id = getIncrementId();
		goods.setId(id);
		String key = "goods:" + id;
		return jedis.set(key, goods.toString()).equals("OK");
	}
	
	/**
	 * 修改商品
	 * @param goods
	 * @return
	 */
	public boolean editGoods(Goods goods) {
		String key = "goods:" + goods.getId();
		if(jedis.exists(key)) {
			return jedis.set(key, goods.toString()).equals("OK");
		}
		return false;
	}
	
	/**
	 * 读取商品总数
	 * @return
	 */
	public long getTotalCount() {
		String key = "goods:count";
		return NumberUtils.toLong(jedis.get(key));
	}
	
	/**
	 * 读取用于分页的商品列表
	 * @param pageIndex 页数
	 * @param pageSize 每页显示行数
	 * @return
	 */
	public List<Goods> getGoodsList(int pageIndex, int pageSize) {
		int totals = (int)getTotalCount();
		int from = (pageIndex - 1) * pageSize;
		if(from < 0) {
			from = 0;
		}
		else if(from > totals) {
			from = (totals / pageSize) * pageSize;
		}
		int to = from + pageSize;
		if(to > totals) {
			to = totals;
		}
		String[] keys = new String[(int)(to - from)];
		for(int i = from; i < to; i++) {
			keys[i - from] = "goods:" + (i + 1);
		}
		List<String> list = jedis.mget(keys);
		List<Goods> goodsList = new ArrayList<>();
		for(String value : list) {
			goodsList.add(Goods.parseJson(value));
		}
		return goodsList;
	}
	
	public void clear() {
		jedis.flushDB();
	}
}
Goods.java
import com.alibaba.fastjson.JSON;

public class Goods {

	public Goods() {}
	
	public Goods(long id, String title, float price) {
		super();
		this.id = id;
		this.title = title;
		this.price = price;
	}
	
	private long id;
	private String title;
	private float price;
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	
	public String toString() {
		return JSON.toJSONString(this);
	}
	
	public static Goods parseJson(String json) {
		return JSON.parseObject(json, Goods.class);
	}
}

源码下载

Redis从基础命令到实战之散列类型(Hash)
Redis从基础命令到实战之列表类型(List)
Redis从基础命令到实战之集合类型(Set)
Redis从基础命令到实战之有序集合类型(SortedSet)

你可能感兴趣的:(redis)