Jedis和RedisTemplate 1

简介: 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);
}


目录
相关文章
|
机器学习/深度学习 文字识别 数据挖掘
Visionpro从小白到大佬,第一章了解工具名称和用途
Visionpro从小白到大佬,第一章了解工具名称和用途
4203 0
Visionpro从小白到大佬,第一章了解工具名称和用途
|
10月前
|
Shell Linux API
2026年在OpenClaw(原 Clawdbot、Moltbot)中配置阿里云百炼 API 完整教程
OpenClaw(前身为Clawdbot、Moltbot)作为一款开源AI个人助手,支持本地部署于MacOS、Windows及Linux系统,能通过自然语言指令控制设备、处理自动化任务(如邮件整理、日程管理、市场调研),且兼容Qwen、Claude、GPT等主流大语言模型。阿里云百炼作为企业级大模型服务平台,其API支持OpenAI-compatible接口,可无缝接入OpenClaw,助力调用通义千问3系列等模型能力。本文结合官方技术文档与实操经验,详细拆解从OpenClaw安装、百炼API Key获取到配置验证的全流程,全程无营销词汇,确保操作贴合技术逻辑,适配不同操作系统用户的需求。
1733 6
|
11月前
|
监控 安全 数据建模
阿里云SSL证书活动参考,付费证书248元起,免费证书每用户每年可申请20张
2026年阿里云SSL证书活动推出付费证书248元起、新老用户同享8折优惠,覆盖DV到EV全类型,满足个人网站至金融机构多样化需求。活动包括新用户专区优惠、证书加急部署服务、HTTPS加速网关及域名监控等增值服务。此外,阿里云还为用户提供免费版SSL证书,每个自然年可领20张。
1200 4
阿里云SSL证书活动参考,付费证书248元起,免费证书每用户每年可申请20张
|
12月前
|
SQL 监控 druid
【性能优化】拒绝性能瓶颈!数据库连接池配置详解与调优实战
本文深入讲解数据库连接池核心原理与调优技巧,涵盖HikariCP和Druid配置要点,解析四大关键参数、黄金连接数公式及Druid监控功能,助你科学设置连接池,避免性能瓶颈。
|
12月前
|
人工智能 运维 物联网
搞定多模态微调只需一杯咖啡的时间?FC DevPod + Llama-Factory 极速实战
告别显存不足、环境配置难与高昂成本!本文带你用阿里云函数计算FC + Llama-Factory,5分钟搭建Qwen2-VL多模态模型的Serverless微调流水线。无需运维,按需付费,通过WebUI点击完成数据准备、LoRA微调、效果验证与模型导出,让AI训练像P图一样简单。低成本、高效率,人人皆可玩转大模型。
|
NoSQL 算法 Java
Java Redis多限流
通过本文的介绍,我们详细讲解了如何在Java中使用Redis实现三种不同的限流策略:固定窗口限流、滑动窗口限流和令牌桶算法。每种限流策略都有其适用的场景和特点,根据具体需求选择合适的限流策略可以有效保护系统资源和提高服务的稳定性。
768 18
|
SQL 监控 druid
Druid连接池学习
Druid学习笔记,使用Druid进行密码加密。参考文档:https://github.com/alibaba/druid
2355 84
|
存储 监控 数据可视化
淘宝API实时竞品监控,市场策略快人一步!
在电商竞争中,实时掌握竞品动态至关重要。本文详解如何利用淘宝开放API构建竞品监控系统,实现价格、库存、促销等数据的自动化采集与分析,帮助企业快速响应市场变化,优化定价、促销与库存策略,提升市场竞争力。
1131 0
|
JSON NoSQL Java
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)
这篇文章介绍了在Java中使用Redis客户端的几种方法,包括Jedis、SpringDataRedis和SpringBoot整合Redis的操作。文章详细解释了Jedis的基本使用步骤,Jedis连接池的创建和使用,以及在SpringBoot项目中如何配置和使用RedisTemplate和StringRedisTemplate。此外,还探讨了RedisTemplate序列化的两种实践方案,包括默认的JDK序列化和自定义的JSON序列化,以及StringRedisTemplate的使用,它要求键和值都必须是String类型。
redis的java客户端的使用(Jedis、SpringDataRedis、SpringBoot整合redis、redisTemplate序列化及stringRedisTemplate序列化)