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


目录
相关文章
|
缓存 小程序 前端开发
【Uniapp】小程序携带Token请求接口+无感知登录方案2.0
【Uniapp】小程序携带Token请求接口+无感知登录方案2.0
659 0
|
数据采集 缓存 定位技术
网络延迟对Python爬虫速度的影响分析
网络延迟对Python爬虫速度的影响分析
|
4月前
|
存储 缓存 分布式计算
阿里云服务器热门实例选择指南:经济型/通用型/计算型性能解析与场景适配
当我们通过阿里云的活动选购云服务器时,常常会面临一个令人困惑的选择:相同配置的云服务器,为何存在多个不同的实例类型,且价格差异显著。这背后的原因在于不同实例规格采用了各异的处理器和底层架构,例如常见的X86计算架构与Arm计算架构,这些差异直接导致了云服务器在性能表现和适用场景上的不同。本文将为大家深入剖析阿里云的经济型、通用算力型、计算型、通用型和内存型实例的性能特点及适用场景,以供选择参考。
|
9月前
|
机器学习/深度学习 缓存 人工智能
《DeepSeek在高并发下的性能秘籍:稳定性与速度保障》
DeepSeek是一款基于Transformer架构的大语言模型,专为高并发场景设计。通过自注意力机制、分布式系统和负载均衡技术,DeepSeek能高效处理多请求,确保稳定性和快速响应。其缓存机制加速数据获取,模型优化提升计算效率,动态资源调配灵活应对流量波动。这些技术共同作用,使DeepSeek在智能客服、内容推荐等场景中表现出色,成为高并发应用的理想选择。
957 10
|
8月前
|
存储 人工智能 Serverless
10 分钟打造你的专属 AI 客服
10 分钟打造你的专属 AI 客服
260 9
|
Java Spring
Spring Boot 中的事务传播行为是什么,原理,如何使用
Spring Boot 中的事务传播行为是什么,原理,如何使用
|
Ubuntu PyTorch 算法框架/工具
Python程序运行,“libgcc_s.so.1 must be installed for pthread_cancel to work”解决办法
Python程序运行,“libgcc_s.so.1 must be installed for pthread_cancel to work”解决办法
480 0
|
机器学习/深度学习 数据采集 数据挖掘
数据分享|SAS数据挖掘EM贷款违约预测分析:逐步Logistic逻辑回归、决策树、随机森林
数据分享|SAS数据挖掘EM贷款违约预测分析:逐步Logistic逻辑回归、决策树、随机森林
|
存储 监控 数据可视化
【BPM技术】Zeebe是一个用于微服务编排的工作流引擎。
【BPM技术】Zeebe是一个用于微服务编排的工作流引擎。
|
API 开发工具 开发者
钉钉中,userid、unionid和staffId
钉钉中,userid、unionid和staffId
2232 2