目录




  • 1 Jedis简介
  • 1.1 编程语言与redis
  • 1.2 准备工作
  • 1.3 代码实现
  • 2 Jedis简易工具类开发
  • 2.1 基于连接池获取连接
  • 2.2 封装连接参数
  • 2.3 加载配置信息
  • 2.4 获取连接
  • 3 可视化客户端
  • 4 RedisTemplate
  • 4.1 开发步骤
  • String类型相关操作
  • 哈希类型相关操作
  • SET类型相关操作
  • LIST类型相关操作

1 Jedis简介

1.1 编程语言与redis

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SGoLIN2Y-1608002733268)(img\jedis1.png)]

对于我们现在的数据来说,它是在我们的redis中,而最终我们是要做程序。那么程序就要和我们的redis进行连接。干什么事情呢?两件事:程序中有数据的时候,我们要把这些数据全部交给redis管理。同时,redis中的数据还能取出来,回到我们的应用程序中。那在这个过程中,在Java与redis之间打交道的这个东西就叫做Jedis.简单说,Jedis就是提供了Java与redis的连接服务的,里边有各种各样的API接口,你可以去调用它。

除了Jedis外,还有没有其他的这种连接服务呢?其实还有很多,了解一下:

Java语言连接redis服务 Jedis(SpringData、Redis 、 Lettuce)

其它语言:C 、C++ 、C# 、Erlang、Lua 、Objective-C 、Perl 、PHP 、Python 、Ruby 、Scala

1.2 准备工作

(1)jar包导入

下载地址:https://mvnrepository.com/artifact/redis.clients/jedis

基于maven

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

(2)客户端连接redis

连接redis

Jedis jedis = new Jedis("localhost", 6379);

操作redis

jedis.set("name", "itheima");  jedis.get("name");

关闭redis连接

jedis.close();

API文档

http://xetorthio.github.io/jedis/

1.3 代码实现

创建:com.itheima.JedisTest

public class JedisTest {

    public static void main(String[] args) {
        //1.获取连接对象
        Jedis jedis = new Jedis("192.168.40.130",6379);
        //2.执行操作
        jedis.set("age","39");
        String hello = jedis.get("hello");
        System.out.println(hello);
        jedis.lpush("list1","a","b","c","d");
        List<String> list1 = jedis.lrange("list1", 0, -1);
        for (String s:list1 ) {
            System.out.println(s);
        }
        jedis.sadd("set1","abc","abc","def","poi","cba");
        Long len = jedis.scard("set1");
        System.out.println(len);
        //3.关闭连接
        jedis.close();
    }
}

2 Jedis简易工具类开发

前面我们做的程序还是有点儿小问题,就是我们的Jedis对象的管理是我们自己创建的,真实企业开发中是不可能让你去new一个的,那接下来咱们就要做一个工具类,简单来说,就是做一个创建Jedis的这样的一个工具。

2.1 基于连接池获取连接

JedisPool:Jedis提供的连接池技术

poolConfig:连接池配置对象

host:redis服务地址

port:redis服务端口号

JedisPool的构造器如下:

public JedisPool(GenericObjectPoolConfig poolConfig, String host, int port) {
this(poolConfig, host, port, 2000, (String)null, 0, (String)null);
}

2.2 封装连接参数

创建jedis的配置文件:jedis.properties

jedis.host=192.168.40.130  
jedis.port=6379  
jedis.maxTotal=50  
jedis.maxIdle=10

2.3 加载配置信息

创建JedisUtils:com.itheima.util.JedisUtils,使用静态代码块初始化资源

public class JedisUtils {
    private static int maxTotal;
    private static int maxIdel;
    private static String host;
    private static int port;
    private static JedisPoolConfig jpc;
    private static JedisPool jp;

    static {
        ResourceBundle bundle = ResourceBundle.getBundle("redis");
        maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));
        maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel"));
        host = bundle.getString("redis.host");
        port = Integer.parseInt(bundle.getString("redis.port"));
        //Jedis连接池配置
        jpc = new JedisPoolConfig();
        jpc.setMaxTotal(maxTotal);
        jpc.setMaxIdle(maxIdel);
        jp = new JedisPool(jpc,host,port);
    }

}

2.4 获取连接

对外访问接口,提供jedis连接对象,连接从连接池获取,在JedisUtils中添加一个获取jedis的方法:getJedis

public static Jedis getJedis(){
	Jedis jedis = jedisPool.getResource();
	return jedis;
}

3 可视化客户端

Redis Desktop Manager

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PO4MK8PZ-1608002733270)(img\可视化.png)]

4 RedisTemplate

4.1 开发步骤

引入依赖

<!--redis客户端jedis依赖-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.7.3</version>
</dependency>
<!-- redis Spring 基于注解配置 -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.2.RELEASE</version>
</dependency>

配置JedisTemplate Bean

xml版本

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="1" />
    <property name="maxTotal" value="5" />
    <property name="blockWhenExhausted" value="true" />
    <property name="maxWaitMillis" value="30000" />
    <property name="testOnBorrow" value="true" />
</bean>

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="localhost" />
    <property name="port" value="6379"/>
    <property name="poolConfig" ref="jedisPoolConfig" />
    <property name="usePool" value="true"/>
</bean>

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory"  ref="jedisConnectionFactory" />
    <property name="keySerializer">
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    </property>
    <property name="valueSerializer">
        <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
    </property>
    <property name="hashKeySerializer">
        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
    </property>
    <property name="hashValueSerializer">
        <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
    </property>
</bean>

注解版本

package com.itheima.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@PropertySource("redis.properties")
public class RedisConfig {

    @Value("${redis.host}")
    private String hostName;

    @Value("${redis.port}")
    private Integer port;

//    @Value("${redis.password}")
//    private String password;

    @Value("${redis.maxActive}")
    private Integer maxActive;
    @Value("${redis.minIdle}")
    private Integer minIdle;
    @Value("${redis.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.maxWait}")
    private Integer maxWait;



    @Bean
    //配置RedisTemplate
    public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        //1.创建对象
        RedisTemplate redisTemplate = new RedisTemplate();
        //2.设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //3.设置redis生成的key的序列化器,对key编码进行处理
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        //4.返回
        return redisTemplate;
    }

    @Bean
    //配置Redis连接工厂
    public RedisConnectionFactory createRedisConnectionFactory(RedisStandaloneConfiguration redisStandaloneConfiguration,GenericObjectPoolConfig genericObjectPoolConfig){
        //1.创建配置构建器,它是基于池的思想管理Jedis连接的
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder builder = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder)JedisClientConfiguration.builder();
        //2.设置池的配置信息对象
        builder.poolConfig(genericObjectPoolConfig);
        //3.创建Jedis连接工厂
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,builder.build());
        //4.返回
        return jedisConnectionFactory;
    }

    @Bean
    //配置spring提供的Redis连接池信息
    public GenericObjectPoolConfig createGenericObjectPoolConfig(){
        //1.创建Jedis连接池的配置对象
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        //2.设置连接池信息
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        //3.返回
        return genericObjectPoolConfig;
    }


    @Bean
    //配置Redis标准连接配置对象
    public RedisStandaloneConfiguration createRedisStandaloneConfiguration(){
        //1.创建Redis服务器配置信息对象
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        //2.设置Redis服务器地址,端口和密码(如果有密码的话)
        redisStandaloneConfiguration.setHostName(hostName);
        redisStandaloneConfiguration.setPort(port);
//        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        //3.返回
        return redisStandaloneConfiguration;
    }

}

编写测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceImplTest {

    @Autowired
    private RedisTemplate redisTemplate;
   

    @Test
    public void set(){
        redisTemplate.opsForValue().set("age","45");
    }
    @Test
    public void get(){
        Object age = redisTemplate.opsForValue().get("age");
        System.out.println(age);
    }
}

RedisTemplate对象结构

redistemplate是原子操作吗 redistemplate和jedis_spring

public void changeMoney(Integer id, Double money) {
    redisTemplate.opsForValue().set("account:id:"+id,money);
}
public Double findMondyById(Integer id) {
    Object money = redisTemplate.opsForValue().get("account:id:" + id);
    return new Double(money.toString());
}

String类型相关操作

1、获取缓存

/**
     * 获取缓存
     * @param key 键
     * @return 值
     */
public Object get(String key){
    return key==null?null:redisTemplate.opsForValue().get(key);
}

2、添加缓存

/**
     * 添加缓存
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
public boolean set(String key,Object value) {
    try {
        redisTemplate.opsForValue().set(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

带有JSON操作:

public class Springboot01ApplicationTests {
    @Autowired
    private AccountService accountService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Test
    public void contextLoads() throws Exception {
        List<Account> list = accountService.findAll();
       String json = new ObjectMapper().writeValueAsString(list);
        System.out.println(json);
        redisTemplate.opsForValue().set("json", json);
        String list1 = redisTemplate.opsForValue().get("json");
        ArrayList<Account> arrayList = new ObjectMapper().readValue(list1, ArrayList.class);

        System.out.println(arrayList);
    }
}

3、添加缓存并设置过期时间

Dart

/**
     * 添加缓存并设置过期时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
public boolean set(String key,Object value,long time){
    try {
        if(time>0){
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        }else{
            set(key, value);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

4、递增操作

Java

/**
     * 递增
     * @param key 键
     * @return
     */
public long incr(String key, long delta){
    if(delta<0){
        throw new RuntimeException("递增因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, delta);
}

5、递减操作

Java

/**
     * 递减
     * @param key 键
     * @return
     */
public long decr(String key, long delta){
    if(delta<0){
        throw new RuntimeException("递减因子必须大于0");
    }
    return redisTemplate.opsForValue().increment(key, -delta);
}

哈希类型相关操作

1、设置一组Map的键值对

Dart

/**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
public Object hget(String key,String item){
    return redisTemplate.opsForHash().get(key, item);
}

2、获取指定Map的所有键值对

Dart

/**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
public Map<Object,Object> hmget(String key){
    return redisTemplate.opsForHash().entries(key);
}

3、添加一个Map类型值

Dart

/**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
public boolean hmset(String key, Map<String,Object> map){
    try {
        redisTemplate.opsForHash().putAll(key, map);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

4、添加一个Map类型值并设置过期时间

Dart

/**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
public boolean hmset(String key, Map<String,Object> map, long time){
    try {
        redisTemplate.opsForHash().putAll(key, map);
        if(time>0){
            expire(key, time);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

5、 向一张hash表中放入数据,如果不存在将创建

Dart

/**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
public boolean hset(String key,String item,Object value) {
    try {
        redisTemplate.opsForHash().put(key, item, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

6、向一张hash表中放入数据,如果不存在将创建并设置过期时间

Dart

/**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
public boolean hset(String key,String item,Object value,long time) {
    try {
        redisTemplate.opsForHash().put(key, item, value);
        if(time>0){
            expire(key, time);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

7、删除hash表中的值

Dart

/**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
public void hdel(String key, Object... item){
    redisTemplate.opsForHash().delete(key,item);
}

8、判断hash表中是否有该项的值

Dart

/**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
public boolean hHasKey(String key, String item){
    return redisTemplate.opsForHash().hasKey(key, item);
}

9、递增,如果不存在,就会创建一个 并把新增后的值返回

Dart

/**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param item 项
     * @param by 要增加几(大于0)
     * @return
     */
public double hincr(String key, String item,double by){
    return redisTemplate.opsForHash().increment(key, item, by);
}

10、递减

Dart

/**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
public double hdecr(String key, String item,double by){
    return redisTemplate.opsForHash().increment(key, item,-by);
}

SET类型相关操作

1、根据key获取Set中的所有值

Dart

/**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
public Set<Object> sGet(String key){
    try {
        return redisTemplate.opsForSet().members(key);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

2、根据value从一个set中查询,是否存在

Dart

/**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
public boolean sHasKey(String key,Object value){
    try {
        return redisTemplate.opsForSet().isMember(key, value);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

3、添加一个SET缓存

Dart

/**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
public long sSet(String key, Object...values) {
    try {
        return redisTemplate.opsForSet().add(key, values);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

4、添加一个SET缓存并设置过期时间

Java

/**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
public long sSetAndTime(String key,long time,Object...values) {
    try {
        Long count = redisTemplate.opsForSet().add(key, values);
        if(time>0) expire(key, time);
        return count;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

5、获取SET缓存的长度

Java

/**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
public long sGetSetSize(String key){
    try {
        return redisTemplate.opsForSet().size(key);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

6、移除指定key的缓存

Kotlin

/**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
public long setRemove(String key, Object ...values) {
    try {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

LIST类型相关操作

1、获取list缓存的内容

Dart

/**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
public List<Object> lGet(String key,long start, long end){
    try {
        return redisTemplate.opsForList().range(key, start, end);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

2、 获取list缓存的长度

Java

/**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
public long lGetListSize(String key){
    try {
        return redisTemplate.opsForList().size(key);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

3、通过索引 获取list中的值

Java

/**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
public Object lGetIndex(String key,long index){
    try {
        return redisTemplate.opsForList().index(key, index);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

4、 将list放入缓存

Dart

/**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
public boolean lSet(String key, Object value) {
    try {
        redisTemplate.opsForList().rightPush(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

5、将list放入缓存并设置过期时间

Java

/**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
public boolean lSet(String key, Object value, long time) {
    try {
        redisTemplate.opsForList().rightPush(key, value);
        if (time > 0) expire(key, time);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

6、将list放入缓存

Dart

/**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
public boolean lSet(String key, List<Object> value) {
    try {
        redisTemplate.opsForList().rightPushAll(key, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

7、将list放入缓存并设置过期时间

Dart

/**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return
     */
public boolean lSet(String key, List<Object> value, long time) {
    try {
        redisTemplate.opsForList().rightPushAll(key, value);
        if (time > 0) expire(key, time);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

8、根据索引修改list中的某条数据

Dart

/**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
public boolean lUpdateIndex(String key, long index,Object value) {
    try {
        redisTemplate.opsForList().set(key, index, value);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

9、移除N个值为value

Csharp

/**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
public long lRemove(String key,long count,Object value) {
    try {
        Long remove = redisTemplate.opsForList().remove(key, count, value);
        return remove;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}