Java代码操作Redis简单应用

 引入Redis相关依赖:

<!--commons-pool2不需要引入,会自动依赖-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.4.2</version>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

工具类:

package com.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
public class RedisUtils {
	//定义连接池独享
	private static JedisPool jedisPool;
	private static String HOST = "47.112.11.147";
	private static int PORT = 6379;
	//连接超时时间单位毫秒数
	private static int TIMEOUT = 6*1000;
	private static String PASSWORD = "123456";
	//连接耗尽时是否阻塞,false报异常,true阻塞直到超时(默认)
	private static boolean isBlock = true;

	static {
		// 使用连接池
		// 【2】创建JedisPool所需的连接池配置
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		//最大连接数,默认8
		//最大的Jedis实例数(连接池是Jedis实例,默认是8)
		poolConfig.setMaxTotal(1024);
		// 最大空闲数,默认8
		//最大的空闲实例数,设置这个可以保留足够的连接,快速获取到Jedis对象
		poolConfig.setMaxIdle(200);
		// 最小空闲连接数,默认0
		poolConfig.setMinIdle(0);
		// 对象最小空闲时间,默认1800000毫秒(30分钟)
		poolConfig.setMinEvictableIdleTimeMillis(1800000);
		// 获取连接的最大等待毫秒数。如果设为小于0,则永远等待
		poolConfig.setMaxWaitMillis(-1);
		// 在创建对象时检测对象是否有效,true是,默认值是false
		poolConfig.setTestOnCreate(true);
		//从对象池获取对象时检测对象是否有效,默认false
		//提前检查Jedis对象,为true获取的Jedis一定是可用的
		poolConfig.setTestOnBorrow(true);
		//在向对象池中归还对象时是否检测对象有效,true是,默认值是false
		poolConfig.setTestOnReturn(false);
		//在检测空闲对象线程检测到对象不需要移除时,是否检测对象的有效性。true是,默认值是false
		poolConfig.setTestWhileIdle(false);
		//检测空闲对象线程每次检测的空闲对象的数量。默认值是3;如果这个值小于0,则每次检测的空闲对象数量等于当前空闲对象数量除以这个值的绝对值,并对结果向上取整
		poolConfig.setNumTestsPerEvictionRun(3);
		//是否启用后进先出, 默认true
		poolConfig.setLifo(true);
		//多长时候执行一次空闲对象检测。单位是毫秒数。如果小于等于0,则不执行检测线程。默认值是-1
		poolConfig.setTimeBetweenEvictionRunsMillis(-1);
		//当对象池没有空闲对象时,新的获取对象的请求是否阻塞。true阻塞。默认值是true;
		poolConfig.setBlockWhenExhausted(isBlock);
		//是否启用pool的jmx管理功能, 默认true
		poolConfig.setJmxEnabled(true);
		//【1】创建JedisPool连接池
		jedisPool = new JedisPool(poolConfig, HOST, PORT, TIMEOUT, PASSWORD);
	}

    /**
     * 同步获取Jedis
     * @return
     */
    public synchronized static Jedis getJedis() {
        if (jedisPool != null) {
            //获取Jedis对象
            Jedis jedis = jedisPool.getResource();
            return jedis;
        }
        return null;
    }

    /**
     * 释放jedis资源
     */
    public static void releaseResource(Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}

测试:

package com.redis;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.BinaryClient;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.Tuple;

import java.util.*;

public class RedisTest {
    private Jedis jedis;
    /**
     * 连接redis服务
     */
    @Test
    public void connectionRedis() {
        //连接远程的Redis服务
        Jedis jedis = new Jedis("47.112.11.147", 6379);
        // 如果有密码,则需要下面权限认证
        jedis.auth("123456");
        System.out.println("连接成功!");
        // 查看服务是否运行
        System.out.println("服务正在运行:" + jedis.ping());
    }

    @Before
    public void getJedis() {
        jedis = RedisUtils.getJedis();
    }

    @After
    public void closeJedis(){
        RedisUtils.releaseResource(jedis);
    }

    /**
     * String类型
     */
    @Test
    public void testString(){
        //添加字符串
        jedis.set("breakfast", "豆浆和包子");
        String mybreak=jedis.get("breakfast");
        System.out.println("我的早餐是:"+mybreak);
        //追加字符串
        jedis.append("breakfast","xxxx");
        System.out.println("追加之后的字符串为:"+jedis.get("breakfast"));

        //一次添加多个key-value
        jedis.mset("k1","v1","k2","v2");
        System.out.println("一次设置多个字符串类型的值:"+jedis.mget("k1","k2"));
    }

    /**
     * Hash类型
     */
    @Test
    public void testHash(){
        //设置hash类型,key:loginuser ,field:username,value: zhangsan
        jedis.hset("loginuser", "username", "zhangsan");
        System.out.println(jedis.hget("loginuser", "username"));


        Map<String,String> map=new HashMap<String,String>();
        map.put("username", "bjpowernode");
        map.put("age", "20");
        map.put("website", "www.bjpowernode.com");
        //设置多个值使用Map,存入Redis
        jedis.hmset("logininfo", map);
        //从redis取hash数据
        List<String> fieldValues=jedis.hmget("logininfo", "username","website","age");
        System.out.println(fieldValues);
        //存在username吗?
        System.out.println("是否存在username-->"+jedis.hexists("logininfo", "username"));
        //查看所有的field
        Set<String> set = jedis.hkeys("logininfo");
        System.out.println(set);
        //删除field:age
        jedis.hdel("logininfo","age");
        System.out.println("age是null-->"+jedis.hget("logininfo", "age"));
        //field的数量
        System.out.println("field的数量:"+jedis.hlen("logininfo"));

    }

    /**
     * List类型
     */
    @Test
    public void testList() {
        String key ="framework";
        jedis.del(key);
        jedis.lpush(key, "mybatis");
        jedis.lpush(key, "hibernate","spring","springmvc");
        List<String> lList = jedis.lrange(key,0, -1);
        System.out.println(lList);

        System.out.println("列表长度:"+jedis.llen(key));
        System.out.println("插入新值后列表的长度"+jedis.linsert(key, BinaryClient.LIST_POSITION.BEFORE,"spring" , "PHP"));
        //从列表右侧插入数据
        jedis.rpush(key, "struts","webwork");
        System.out.println("列表数据:"+jedis.lrange(key, 0, -1));

        System.out.println("下标为1的数据为:"+jedis.lindex(key, 1));
        for(long  i=0;i<jedis.llen(key);i++){
            System.out.println("弹出:"+jedis.lpop(key));
        }
    }


    /**
     * Set类型
     */
    @Test
    public void testSet() {
        String key ="course";
        //添加一个数据
        jedis.sadd(key, "html");
        //添加的个数据
        jedis.sadd(key, "spring","springmvc");
        System.out.println("set集合中的数据为:"+jedis.smembers(key));
        System.out.println("判断spring是否在set集合中:"+jedis.sismember(key, "spring"));
        System.out.println("集合中的数量:"+jedis.scard(key));
    }


    /**
     * ZSet类型
     */
    @Test
    public void testZSet(){
        String key ="salary";
        jedis.del(key);
        jedis.zadd(key,2000.0,"john");
        //添加多个数据
        Map<String,Double> map=new HashMap<>();
        map.put("tom",3500.0);
        map.put("zs", 12000d);

        jedis.zadd(key, map);

        Set<String> set=jedis.zrangeByScore(key, "-inf", "+inf");
        System.out.println(set);

        //带有score的数据
        Set<Tuple> tuple=jedis.zrangeByScoreWithScores(key, "-inf", "+inf");
        Iterator<Tuple> iterator=tuple.iterator();
        while(iterator.hasNext()){
            Tuple next = iterator.next();
            System.out.println("带分数,排序小-->大:"+next.getElement()+""+next.getScore());
        }
        System.out.println("带分数"+tuple);
        System.out.println("成员的数量:"+jedis.zcard(key));
    }

    /**
     * 事务
     */
    @Test
    public void testTransaction(){
        //开启事务
        Transaction tran=jedis.multi();
        tran.set("breakfast", "油条和包子");
        tran.set("lunch", "大米");
        List<Object> result = tran.exec();
        System.out.println("事务的结果:"+result);
    }
}

参考:java代码操作Redis数据库

猜你喜欢

转载自blog.csdn.net/qq_39669058/article/details/89139083
今日推荐