springboot学习(二)--Jedis整合

项目目录如下:

一、引入jar包

创建好springboot项目后在pom.xml文件引入相应jar包(redis、jedis的jar包):

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

二、配置redis

redis.properties文件如下,这里只做简单配置:

redis.host=192.168.126.130
redis.port=6379
redis.password=123456
redis.database=0
redis.timeout=10000

三、自动化配置jedis

也就是RedisConfig.java文件,代码如下:

@Configuration
@Component
/*
* 这里应用springboot的属性安全注入
* */
@PropertySource("classpath:redis.properties")
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
    private String host;
    private int port;
    private String password;
    private int database;
    private int timeout;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getDatabase() {
        return database;
    }

    public void setDatabase(int database) {
        this.database = database;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
    private Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    public JedisPool jedisPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        JedisPool jedisPool = null;
        try {
            //设置最大连接数(100个足够用了,没必要设置太大)
            config.setMaxTotal(100);
            //最大空闲连接数
            config.setMaxIdle(10);
            //获取Jedis连接的最大等待时间(50秒)
            config.setMaxWaitMillis(50 * 1000);
            //在获取Jedis连接时,自动检验连接是否可用
            config.setTestOnBorrow(true);
            //在将连接放回池中前,自动检验连接是否有效
            config.setTestOnReturn(true);
            //自动测试池中的空闲连接是否都是可用连接
            config.setTestWhileIdle(true);
            jedisPool = new JedisPool(config,host,port,timeout,password);
            jedisPool.getResource();
        }catch (JedisConnectionException e){
            String message = e.getMessage();
            if("Could not get a resource from the pool".equalsIgnoreCase(message)){
                System.out.println("++++++++++请检查你的redis服务++++++++");
                System.out.println("①.请检查是否安装redis服务.");
                System.out.println("②.请检查redis 服务是否启动。");
                System.out.println("③.请检查redis启动是否带配置文件启动,也就是是否有密码,是否端口有变化(默认6379)。");
                System.exit(0);//停止项目
            }
            throw new JedisConnectionException(e);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        System.out.println("++++++++++redis连接成功++++++++++");
        return jedisPool;
    }

    /*
    * 注入jdis连接池
    * */
    @Bean
    public RedisUtil redisUtil(JedisPool jedisPool){
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setJedisPool(jedisPool);
        return redisUtil;
    }
}

 上面代码中我们将Jedis注入到了我们的逛逛方法工具类中(RedisUtil),具体看上面注释,方法工具类如下:

public class RedisUtil {
    private JedisPool jedisPool;

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public Jedis getJedis() {
        return getJedisPool().getResource();
    }

    public void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
        jedis.close();
    }

    /**
     * @code 根据key获取值
     * @param dbIndex
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        byte[] result = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return result;
    }

    /**
     * @code:根据key删除某个数据
     * @param dbIndex
     * @param key
     * @throws Exception
     */
    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            Long result = jedis.del(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }

    /**
     * @code:新增数据
     * @param dbIndex
     * @param key
     * @param value
     * @param expireTime
     * @throws Exception
     */
    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)
            throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }
}

四、序列化、反序列化工具类

工具类:SerializableUtil

public class SerializableUtil {

    /**
     * 将对象序列化
     */
    public static byte[] serializableObject(Object value){
        byte[] bt = null;
        ObjectOutputStream os = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            os = new ObjectOutputStream(bos);
            os.writeObject(value);
            bt = bos.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
                bos.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return bt;
    }
    /*
    * 将对象反序列化
    * */
    public static  <T>T deserialize(byte[] bt,Class<T> clzz){
        ObjectInputStream os = null;
        ByteArrayInputStream bs = null;
        Object obj = new Object();
        try {
            if(bt != null) {
                bs = new ByteArrayInputStream(bt);
                os = new ObjectInputStream(bs);
                obj = os.readObject();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
                bs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return (T)obj;
    }
}

五、测试

创建User类,注意实体类要实现 Serializable 接口,否则会报错误。

public class User implements Serializable {
    private int id;
    private String name;
    private int age;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

测试方法:

 @Test
    void contextLoads() {
        String key = "user_key";
        User user = new User();
        user.setAge(21);
        user.setId(1);
        user.setName("李四");
        byte[] bytes_key = SerializableUtil.serializableObject(key);
        byte[] value_value = SerializableUtil.serializableObject(user);
        try {
            redisUtil.saveValueByKey(0,bytes_key,value_value,0);
            byte[] user_byte = redisUtil.getValueByKey(0, bytes_key);
            User user2 = SerializableUtil.deserialize(user_byte, User.class);
            System.out.println(user2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*Jedis jedis = new Jedis("192.168.126.130",6379);
        jedis.auth("123456");
        String ping = jedis.ping();
        System.out.println(ping);*/
    }

运行结果如下:

这里springboot简单整合Jedis就成功了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值