Redis学习笔记(三):Java连接Redis(Jedis)以及示例代码

Redis学习笔记系列

  • Redis学习笔记(一):下载与安装-Windows、Linux
  • Redis学习笔记(二):数据类型和通用操作命令
  • Redis学习笔记(三):Java连接Redis(Jedis)以及示例代码
  • Redis学习笔记(四):Redis持久化
  • Redis学习笔记(五):Redis事务-multi、exec、discard、锁、分布式锁、死锁
  • Redis学习笔记(六):删除策略、逐出算法
  • Redis学习笔记(七):redis高级数据类型及应用场景-Bitmaps、HyperLogLog、GEO
  • Redis学习笔记(八):redis主从复制-建立连接、数据同步、命令传播、复制缓冲区、复制偏移量、心跳机制
  • Redis学习笔记(九):哨兵模式-监控、通知、故障转移
  • Redis学习笔记(十):Redis集群-结构设计、集群搭建、集群操作、主从下线、主从切换
  • Redis学习笔记(十一):企业级解决方案-缓存预热、缓存雪崩、缓存击穿、缓存穿透、性能指标监控

Jedis简介

  • Jedis是java连接redis服务的途径,但并不是java连接redis的唯一途径,Java连接redis服务有以下途径:

Jedis
SpringData Redis
Lettuce

HelloWorld

  1. jar包导入
    下载地址:https://mvnrepository.com/artifact/redis.clients/jedis
  • Maven
<dependency>
	<groupId>redis.clientsgroupId>
	<artifactId>jedisartifactId>
	<version>3.3.0version>
dependency>
  • Gradle
compile group: 'redis.clients', name: 'jedis', version: '3.3.0'

2.Jedis常规操作:编写代码

  • 连接redis
	@Test
    public void jedisTest(){
        //1.连接redis
        Jedis jedis = new Jedis("127.0.0.1",6379);
        //2.操作redis
        String setResult = jedis.set("sam", "123");
        System.out.println(setResult);
        String value = jedis.get("sam");
        System.out.println(value);
        //3.关闭redis
        jedis.close();
    }

结果输出:

OK
123
  • redis操作List
	@Test
    public void testList(){
        //1.连接redis
        Jedis jedis = new Jedis("127.0.0.1",6379);
        //2.操作redis
        jedis.lpush("list1","a","b","c");
        jedis.rpush("list1","d");
        List<String> list1 = jedis.lrange("list1", 0, -1);
        list1.forEach(s -> {
            System.out.println(s);
        });
        System.out.println(jedis.llen("list1"));
        //3.关闭redis
        jedis.close();
    }

结果输出:

c
b
a
d
4
  • redis操作Hash
	@Test
    public void testHash(){
        //1.连接redis
        Jedis jedis = new Jedis("127.0.0.1",6379);
        //2.操作redis
        jedis.hset("hash1","a","1");
        Map<String,String> hash = new HashMap<>();
        hash.put("b","2");
        hash.put("c","3");
        jedis.hmset("hash1",hash);
        Map<String, String> hash1 = jedis.hgetAll("hash1");
        hash1.entrySet().forEach(h ->{
            System.out.println("key:" + h.getKey() +" value:" + h.getValue());
        });
        System.out.println(jedis.hlen("hash1"));
        //3.关闭redis
        jedis.close();
    }

结果输出:

key:a value:1
key:b value:2
key:c value:3
3

案例:根据用户级别,控制业务请求次数

package com.ysa.redis.demo1;

import com.ysa.redis.demo1.utils.RedisUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;

import java.util.spi.CurrencyNameProvider;

public class RedisService {

    public void control(String id, Integer num){
        Jedis jedis = RedisUtils.getJedis();
        String user = jedis.get("userId:" + id);
        try {
            Long count = Long.MAX_VALUE - num + 1;
            if(user == null){
                jedis.setex("userId:" + id, Integer.parseInt(RedisUtils.getResourceVal(RedisUtils.remoteTime)), String.valueOf(count));
            }else{
                count = jedis.incr("userId:" + id);
            }
            service(id,(num - (Long.MAX_VALUE - count)));
        }catch (JedisDataException e){
            System.out.println("id:"+id+" 调用业务已经超过限制,请升级会员");
        }finally {
            jedis.close();
        }
    }

    public void service(String id, Long count) {
        System.out.println("id: "+id+" 业务操作第" + count + "次");
    }
}

class Customer implements Runnable{
    private String id;
    private Integer num;

    public Customer(String id, Integer num) {
        this.id = id;
        this.num = num;
    }
    RedisService rs = new RedisService();

    @Override
    public void run() {
        while(true){
            rs.control(id, num);
            try {
                Thread.sleep(new Double(500 + Math.random()*500).longValue());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Main{
    public static void main(String[] args) {
        Thread t1 = new Thread(new Customer("初级用户",10));
        Thread t2 = new Thread(new Customer("高级用户",15));
        t1.start();
        t2.start();
    }
}

package com.ysa.redis.demo1.utils;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class RedisUtils {
    public static final String resource_name = "redis";
    public static final String host = "redis.host";
    public static final String port = "redis.port";
    public static final String maxTotal = "redis.maxTotal";
    public static final String maxIdle = "redis.maxIdle";
    public static final String remoteTime = "redis.remoteTime";
    private static Map<String,Object> resource = new HashMap<>();
    static{
        ResourceBundle rb = ResourceBundle.getBundle(resource_name);
        resource.put(host,rb.getObject(host));
        resource.put(port,rb.getObject(port));
        resource.put(maxTotal,rb.getObject(maxTotal));
        resource.put(maxIdle,rb.getObject(maxIdle));
        resource.put(remoteTime,rb.getObject(remoteTime));
    }
    public static Jedis getJedis(){
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(Integer.parseInt(getResourceVal(maxTotal)));
        config.setMaxIdle(Integer.parseInt(getResourceVal(maxIdle)));
        JedisPool jedisPool = new JedisPool(config, getResourceVal(host), Integer.parseInt(getResourceVal(port)));
        return jedisPool.getResource();
    }

    public static String getResourceVal(String key){
        if(resource.containsKey(key)){
            return (String) resource.get(key);

        }else{
            throw new RuntimeException("资源文件中找不到["+key+"]对应的值");
        }
    }
}

redis配置文件redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=20
redis.maxIdle=10
redis.remoteTime=60

运行结果:
Redis学习笔记(三):Java连接Redis(Jedis)以及示例代码_第1张图片

  • 温馨提示

可以使用Redis Desktop Manager可视化客户端查看Redis数据
链接:https://pan.baidu.com/s/1Jhb3_sAQo8vI-55drKv3sA
提取码:6qzq


- 捐赠 -


如果觉得还不错,请我喝杯水吧 ^ _ ^ 您的鼓励是我不断前进的动力,如果有错误的地方,欢迎提出批评改正意见,戳我,感谢您的支持

支付宝 微信

你可能感兴趣的:(Redis学习笔记系列)