Redis--Jedis客户端连接以及Jedis常用方法

1.pom 导出依赖


            redis.clients
            jedis
        

2.开启redis服务 默认端口也要以指定配置文件的方式启动
redis-server /usr/local/tem/redis/redis.conf
3.yml 配置


spring:
  redis:
    host: 虚拟机端口
    port: 6379
    database: 0
    password:
    jedis:
      pool:
        #最大连接数
        max-active: 300
        #最大阻塞等待时间(负数表示没限制)
        max-wait: -1
        #最大空闲
        max-idle: 8
        #最小空闲
        min-idle: 0
    #连接超时时间
    timeout: 100000
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    encoding: UTF-8
    mode: HTML5
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
    username: root
    password: 123
    druid:
      # ???????????
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # ?????????????
      maxWait: 60000
      # ???????????????????????????????
      timeBetweenEvictionRunsMillis: 60000
      # ??????????????????????
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # ??PSCache??????????PSCache???
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # ?????????filters????????sql?????'wall'?????
      filters: stat,wall
      # ??connectProperties?????mergeSql????SQL??
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      # ??DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # ??DruidStatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP???(????????????????)
        allow: 127.0.0.1,192.168.163.1
        # IP??? (??????deny???allow)
        deny: 192.168.1.73
        #  ??HTML?????Reset All???
        reset-enable: false
        # ???
        login-username: admin
        # ????
        login-password: 123456
mybatis-plus:
  #mapper-locations: classpath:/com/example/demo/mapper/*/*.xml
  typeAliasesPackage: com.zhu.redis.entity
  global-config:
    id-type: 2
    field-strategy: 2
    db-column-underline: true
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
server:
  port: 8083



4.配置 RedisConfig

package com.zhu.redis.myconfig;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;

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


    @Bean
    public JedisPool redisPoolFactory()  throws Exception{
        log.info("JedisPool注入成功!!");
        log.info("redis地址:" + host + ":" + port);
        log.info("maxIdle:"+maxIdle);
        log.info("maxWaitMillis"+maxWaitMillis);
        log.info("timeout:"+timeout);
        log.info("password:"+password);
        GenericObjectPoolConfig jedisPoolConfig = new GenericObjectPoolConfig();
        /*jedisPoolConfig.setMaxTotal(200);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(true);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);*/
        log.info("jedisPoolConfig:"+jedisPoolConfig);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port);
           log.info("jedisPool-------"+jedisPool);
        return jedisPool;
    }






}

5.工具类 RedisUtil 常用操作
更多操作请参考
https://blog.csdn.net/zhulier1124/article/details/82193182

package com.zhu.redis.redisclient;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

@Slf4j
@Component
public class RedisUtil {
    @Autowired
    private JedisPool jedisPool;


    /**
     * 

* 通过key获取储存在redis中的value *

*

* 并释放连接 *

* * @param key *@indexdb 选择redis库 0-15 * @return 成功返回value 失败返回null */ public String get(String key,int indexdb) { Jedis jedis = null; String value = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); value = jedis.get(key); log.info(value); } catch (Exception e) { log.error(e.getMessage()); } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } return value; } /** * 存贮字符串 * @param key * @param value * @indexdb 选择redis库 0-15 * @return * 如果key存在则覆盖 */ public String set(String key, String value,int indexdb) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); return jedis.set(key, value); } catch (Exception e) { log.error(e.getMessage()); return "0"; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } } /** *

* 删除指定的key,也可以传入一个包含key的数组 *

* * @param keys 一个key 也可以使 string 数组 * @return 返回删除成功的个数 */ public Long del(String... keys) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.del(keys); } catch (Exception e) { log.error(e.getMessage()); return 0L; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } } /** *

* 通过key向指定的value值追加值 *

* * @param key * @param str * @return 成功返回 添加后value的长度 失败 返回 添加的 value 的长度 异常返回0L */ public Long append(String key, String str) { Jedis jedis = null; Long res = null; try { jedis = jedisPool.getResource(); res = jedis.append(key, str); } catch (Exception e) { log.error(e.getMessage()); return 0L; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } return res; } /** *

* 判断key是否存在 *

* * @param key * @return true OR false */ public Boolean exists(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.exists(key); } catch (Exception e) { log.error(e.getMessage()); return false; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } } /** *

* 清空当前数据库中的所有 key,此命令从不失败。 *

* * @return 总是返回 OK */ public String flushDB() { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.flushDB(); } catch (Exception e) { log.error(e.getMessage()); } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } return null; } /** *

* 为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。 *

* * @param key * @param value * 过期时间,单位:秒 * @return 成功返回1 如果存在 和 发生异常 返回 0 */ public Long expire(String key, int value, int indexdb) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); return jedis.expire(key, value); } catch (Exception e) { log.error(e.getMessage()); return 0L; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } } /** *

* 以秒为单位,返回给定 key 的剩余生存时间 *

* * @param key * @return 当 key 不存在时,返回 -2 。当 key 存在但没有设置剩余生存时间时,返回 -1 。否则,以秒为单位,返回 key * 的剩余生存时间。 发生异常 返回 0 */ public Long ttl(String key,int indexdb) { Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.select(indexdb); return jedis.ttl(key); } catch (Exception e) { log.error(e.getMessage()); return 0L; } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } } /** *

* 新增key,并将 key 的生存时间 (以秒为单位) *

* * @param key * @param seconds * 生存时间 单位:秒 * @param value * @return 设置成功时返回 OK 。当 seconds 参数不合法时,返回一个错误。 */ public String setex(String key, int seconds, String value) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.setex(key, seconds, value); } catch (Exception e) { log.error(e.getMessage()); } finally { if (jedis!=null) { //如果使用的是jedisPool获得的jedis close操作不是关闭连接 而是代表归还连接池 jedis.close(); } } return null; } /** * 序列化对象 * @param obj * @return * 对象需实现Serializable接口 */ public static byte[] ObjTOSerialize(Object obj) { ObjectOutputStream oos = null; ByteArrayOutputStream byteOut = null; try { byteOut = new ByteArrayOutputStream(); oos = new ObjectOutputStream(byteOut); oos.writeObject(obj); byte[] bytes = byteOut.toByteArray(); return bytes; } catch (Exception e) { } return null; } /** * 反序列化对象 * @param bytes * @return * 对象需实现Serializable接口 */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { //反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } }

7.测试 Controller

  @Autowired
    private RedisUtil redisUtil;

8.做个小demo 缓存视频基本信息 数据源在mysql

你可能感兴趣的:(liunx)