jedis操作 redis

農夫YH發表於2018-05-31

spring mvc 配置 jedis連線池

首先 maven 依賴 來一下

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

然後配置檔案搞一下

#redis快取配置
redis.host=127.0.0.1
redis.port=6379
redis.timeout=2000
#注意,如果沒有password,此處不設定值,但這一項要保留
redis.password=xxx
redis.db.index=1

然後spring 配置個bean

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="300" /> <!-- 最大能夠保持idel狀態的物件數  -->
        <property name="maxTotal" value="60000" /> <!-- 最大分配的物件數 -->
        <property name="testOnBorrow" value="true" /> <!-- 當呼叫borrow Object方法時,是否進行有效性檢查 -->
    </bean>

    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
        <constructor-arg name="host" value="${redis.host}" />
        <constructor-arg name="port" value="${redis.port}" type="int" />
        <constructor-arg name="timeout" value="${redis.timeout}" type="int" />
        <constructor-arg name="password" value="#{'${redis.password}'!=''?'${redis.password}':null}" />
        <constructor-arg name="database" value="${redis.db.index}" type="int" />
    </bean>

測試類

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml","classpath:mybatis-servlet.xml"})
public class JedisTest {

    @Autowired
    JedisPool pool;

    @Test
    public void jedis(){
        try {
            Jedis jedis=pool.getResource();
            Admins admins = new Admins();
            admins.setName("張三");
            admins.setPwd("lisi");
            jedis.set("admin".getBytes(), SerializeUtil.serialize(admins));
            admins =  (Admins)SerializeUtil.deserialize(jedis.get("admin".getBytes()));
            System.err.println(admins.getName());
        } catch (Exception e) {
            System.err.println(e);
        }


    }

}

中間用到了一個 幫助類

package com.yc.education.util;

import java.io.*;

public class SerializeUtil {

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes) {

        Object result = null;

        if (isEmpty(bytes)) {
            return null;
        }

        try {
            ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
                try {
                    result = objectInputStream.readObject();
                }
                catch (ClassNotFoundException ex) {
                    throw new Exception("Failed to deserialize object type", ex);
                }
            }
            catch (Throwable ex) {
                throw new Exception("Failed to deserialize", ex);
            }
        } catch (Exception e) {
        }
        return result;
    }

    public static boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {

        byte[] result = null;

        if (object == null) {
            return new byte[0];
        }
        try {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
            try  {
                if (!(object instanceof Serializable)) {
                    throw new IllegalArgumentException(SerializeUtil.class.getSimpleName() + " requires a Serializable payload " +
                            "but received an object of type [" + object.getClass().getName() + "]");
                }
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
                objectOutputStream.writeObject(object);
                objectOutputStream.flush();
                result =  byteStream.toByteArray();
            }
            catch (Throwable ex) {
                throw new Exception("Failed to serialize", ex);
            }
        } catch (Exception ex) {

        }
        return result;
    }

}

好了 程式碼貼完了

相關文章