1.创建maven 项目,引入jedis及spring依赖包
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
引入资源后,执行maven install 如果可以看到BUILD SUCCESS 表示成功,下面就可以编写代码了
2.配置Redis
创建spring-redis.xml 用于配置redis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 读取配置文件信息 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:redis.properties" />
<!-- 开启注解扫描 -->
<context:annotation-config/>
<!-- 指定要扫描的包 -->
<context:component-scan base-package="com.bigdata"/>
<!-- redis 配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="minIdle" value="${redis.minIdle}"></property>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="true" />
</bean>
<!-- redis单节点数据库连接配置 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.hostName}" />
<property name="port" value="${redis.port}" />
<property name="password" value="${redis.password}" />
<property name="timeout" value="${redis.timeout}" />
<property name="usePool" value="true"/>
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<!-- redis 模板配置(对key、value进行序列化) -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"></property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
</property>
</bean>
</beans>
redis.properties
###### 连接池 #####
# 最大连接数,默认为8,-1表示不限制
redis.maxTotal = 20
# 最大空闲连接数,默认为8
redis.maxIdle = 10
# 初始化连接数
redis.minIdle = 2
# 最大等待时间,单位为毫秒,默认-1,永不超时,如果超时,抛出异常 JedisConnectionException
redis.maxWaitMillis = 10000
#### 数据库连接 ####
redis.hostName = 192.168.242.161
redis.port = 6379
redis.password = admin
redis.timeout = 15000
3.Spring 集成 Jedis 测试
Spring 中 提供了一个类RedisTemplate,类似于我们Hiberante 框架中提供的HibernateTemplate类,它为我们操作Redis作了封装,直接使用即可,RedisTemp 操作 Redis代码如下
package com.bigdata.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Spring 集成 Jedis 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-redis.xml")
public class Spring2JedisTest {
@Resource
private RedisTemplate redisTemplate;
// Redis String
@Test
public void testString() throws Exception {
redisTemplate.opsForValue().set("name", "jack");
String name = String.valueOf(redisTemplate.opsForValue().get("name"));
System.out.println("name = " + name);
}
// Redis Hash
@Test
public void testHash() throws Exception {
HashOperations opsForHash = redisTemplate.opsForHash();
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "jack");
map.put("address", "BeiJing");
opsForHash.putAll("student", map);
Map<String, Object> entries = opsForHash.entries("student");
for(Map.Entry<String, Object> entry : entries.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
// Redis List
@Test
public void testList() throws Exception {
ListOperations opsForList = redisTemplate.opsForList();
opsForList.rightPush("dblist", "mysql");
opsForList.rightPush("dblist", "redis");
opsForList.rightPush("dblist", "oracle");
List list = opsForList.range("dblist", 0, -1);
for (Object obj : list) {
System.out.println(String.valueOf(obj));
}
}
// Redis Set
@Test
public void testSet() throws Exception {
SetOperations opsForSet = redisTemplate.opsForSet();
opsForSet.add("fruits", "peach", "pear", "banana");
Set members = opsForSet.members("fruits");
for (Object obj : members) {
System.out.println(String.valueOf(obj));
}
}
// Redis ZSet
@Test
public void testZSet() throws Exception {
ZSetOperations opsForZSet = redisTemplate.opsForZSet();
opsForZSet.add("scores", "math", 89.0);
opsForZSet.add("scores", "english", 96.0);
opsForZSet.add("scores", "sports", 78.0);
Set scores = opsForZSet.range("scores", 0, -1);
for (Object obj : scores) {
System.out.println(String.valueOf(obj));
}
}
}
4.User 对象 CRUD
使用上面的User对象,通过RedisTemplate完成对User对象的CRUD,代码如下
UserDao.java
package com.bigdata.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.bigdata.entity.User;
public interface UserDao {
/** 新增 */
public void save(User user);
/** 更新 */
public void update(User user);
/** 删除 */
public void delete(int id, String... keys);
/** 根据主键查询 */
public User getById(int id);
}
UserDaoImpl.java
package com.bigdata.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import com.bigdata.dao.UserDao;
import com.bigdata.entity.User;
@Repository
public class UserDaoImpl implements UserDao {
@Resource
private RedisTemplate redisTemplate;
public void save(User user) {
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("id", user.getId());
userMap.put("name", user.getName());
userMap.put("address", user.getAddress());
redisTemplate.opsForHash().putAll("user:" + String.valueOf(userMap.get("id")), userMap);
}
// 更新与新增的代码一样,新值会覆盖旧值
public void update(User user) {
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("id", user.getId());
userMap.put("name", user.getName());
userMap.put("address", user.getAddress());
redisTemplate.opsForHash().putAll("user:" + String.valueOf(userMap.get("id")), userMap);
}
public void delete(int id, String... keys) {
redisTemplate.opsForHash().delete("user:" + id, keys);
}
public User getById(int id) {
Map userMap = redisTemplate.opsForHash().entries("user:" + id);
return new User(id, String.valueOf(userMap.get("name")), String.valueOf(userMap.get("address")));
}
}
测试类:
package com.bigdata.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bigdata.dao.UserDao;
import com.bigdata.entity.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-redis.xml")
public class UserTest {
@Resource
private UserDao userDao;
@Test
public void testSave() throws Exception {
userDao.save(new User(1, "tom", "ShangHai"));
userDao.save(new User(2, "jack", "GuangZhou"));
userDao.save(new User(3, "mary", "BeiJing"));
}
@Test
public void testUpdate() throws Exception {
userDao.update(new User(1, "david", "ChengDu"));
}
@Test
public void testDelete() throws Exception {
userDao.delete(1, "address");
}
@Test
public void testGetById() throws Exception {
System.out.println(userDao.getById(1));
}
}