Spring整合Redis
1.导包 pom.xml
2.spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--读取配置文件-->
<context:property-placeholder location="classpath:redis.properties"/>
<bean class="redis.clients.jedis.JedisPoolConfig" id="poolConfig">
<!-- 最大等待时间-->
<property name="maxWaitMillis" value="${redis.maxWait}"/>
<!--测试连接-->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxTotal" value="${redis.maxActive}"/>
</bean>
<!--连接池-->
<bean class="redis.clients.jedis.JedisPool" id="jedisPool">
<constructor-arg name="poolConfig" ref="poolConfig"/>
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
<constructor-arg name="password" value="${redis.pass}"/>
<constructor-arg name="database" value="${redis.dbIndex}"/>
<constructor-arg name="timeout" value="${redis.maxWait}"/>
</bean>
</beans>
3.测试
@Test
public void test1(){
ApplicationContext app=new ClassPathXmlApplicationContext("bean_core.xml");
JedisPool pool = app.getBean(JedisPool.class);
Jedis jedis = pool.getResource();
jedis.set("username","admin123");
jedis.close();
}
序列化:
public class SerializeUtil {
/**序列化对象
* @param obj
* @return
*/
public static byte[] serialize(Object obj) {
//防止传空值
if (null==obj) return null;
try {
//内存输出流
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//对象输出流
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(obj);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**反序列化
* @param b
* @return
*/
public static Object deserialize(byte[] b){
if (null==b) return null;
try {
ByteArrayInputStream bis=new ByteArrayInputStream(b);
ObjectInputStream ois=new ObjectInputStream(bis);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}