Jedis和RedisTemplate 1

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Jedis和RedisTemplate

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对象结构

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);
}


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
4天前
|
缓存 负载均衡 监控
请列出与jedis相关的10种技术
列出与jedis相关的10种技术
159 0
|
4天前
|
存储 NoSQL Redis
redisTemplate.opsForHash()
redisTemplate.opsForHash()
|
4天前
|
存储 数据可视化
RedisTemplate中opsForValue()中的方法
RedisTemplate中opsForValue()中的方法
|
4天前
|
存储 NoSQL Redis
RedisTemplate常用方法总结
RedisTemplate常用方法总结
|
4天前
|
NoSQL Java Redis
|
6月前
|
NoSQL Java Redis
jedis分布式锁实现
jedis分布式锁实现
|
7月前
|
JavaScript NoSQL Java
18Redis - Jedis介绍
18Redis - Jedis介绍
17 0
|
8月前
|
缓存 Dart Java
Jedis和RedisTemplate 2
Jedis和RedisTemplate
37 0
|
NoSQL Redis
RedisTemplate和StringRedisTemplate
RedisTemplate和StringRedisTemplate
|
NoSQL Java API
RedisTemplate及其相关方法
RedisTemplate及其相关方法
236 0
RedisTemplate及其相关方法