①需要导入的jar包
-
jedis(java连接redis数据库核心jar包)
-
protostuff(实现序列化,反序列化,性能较好)
<!--redis客户端:jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--Protostuff序列化的依赖-->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>RELEASE</version>
</dependency>
②所在目录
③编写RedisDao,实现学生信息存入redis数据库和从redis数据库中读取存入的学生信息(具体看注释)
public class RedisDao {
//定义redis数据库连接池属性
private final JedisPool jedisPool;
//定义序列化的约束属性
private RuntimeSchema<Student> schema = RuntimeSchema.createFrom(Student.class);
//定义redis数据库连接池配置信息
private static final JedisPoolConfig config;
//静态代码块
static{
config = new JedisPoolConfig();
//设置最大空闲连接数
config.setMaxIdle(10);
//设置最大连接数
config.setMaxTotal(30);
}
//构造函数,类加载时,填写连接属性,获取连接池对象
public RedisDao(String ip, int port) {
jedisPool = new JedisPool(config,ip, port);
}
public Student getStudentFromRedis(int studentID) {
try {
//从数据库连接池中获取一个数据库操作对象
try (Jedis jedis = jedisPool.getResource()) {
//设置key
String key = "studentID:" + studentID;
//没有实现内部序列化操作
//get->byte[]->反序列化->Object()
//采用自定义序列化Protostuff:需要一个空对象
//获取key的字符数组
byte[] bytes = jedis.get(key.getBytes());
if (bytes != null) {
//空对象
Student student = schema.newMessage();
//填充空对象
ProtostuffIOUtil.mergeFrom(bytes, student, schema);
return student;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String putStudentToRedis(Student student) {
//object->序列化->byte[]
try {
try (Jedis jedis = jedisPool.getResource()) {
//设置key
String key = "studentID:" + student.getStudentId();
//将student对象序列化
byte[] bytes = ProtostuffIOUtil.toByteArray(student, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
//超时缓存,缓存的时间
int timeout = 60 * 60;//1小时
//将student对象写入redis
return jedis.setex(key.getBytes(), timeout, bytes);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
④构造注入RedisDao
<!--构造注入RedisDao-->
<bean id="redisDao" class="njupt.test.ssm.dao.cache.RedisDao">
<constructor-arg index="0" value="服务器IP地址"/>
<constructor-arg index="1" value="端口号"/>
</bean>
⑤测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class RedisDaoTest {
@Autowired
RedisDao redisDao;
@Autowired
StudentDao studentDao;
@Test
public void getStudentFromRedis() throws Exception {
Student student = redisDao.getStudentFromRedis(1);
if (student==null){
student=studentDao.queryStudentById(1);
System.out.println(redisDao.putStudentToRedis(student));
System.out.println(redisDao.getStudentFromRedis(1));
}else {
System.out.println(student);
}
}
@Test
public void putStudentToRedis() throws Exception {
}
}