Redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
Redis优势
(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。
简单使用
首先启动Redis服务。
测试代码:
public class RedisTest {
public static void main(String[] args){
//连接Redis服务器
Jedis jedis=new Jedis("localhost");
System.out.println("connection to server successfully");
//测试string类型
jedis.set("kanglixian", "xiaokang");
System.out.println("Server is running:"+jedis.get("kanglixian"));
//测试list类型
jedis.lpush("listIn", "FirstIn");
jedis.lpush("listIn", "SecondIn");
jedis.lpush("listIn", "ThirdIn");
List<String> list=jedis.lrange("listIn", 0, 5);
for(int i=0;i<list.size();i++){
System.out.println("第"+i+"个值:"+list.get(i));
}
//取所有的key
Set<String> set=jedis.keys("*");
Iterator iterator=set.iterator();
while(iterator.hasNext()){
System.out.println("值:"+iterator.next());
}
}
}
控制台结果输出:
与spring结合使用
第一种方法:
目录结构如下:
UserDaoImpl代码:
public class UserDaoImpl implements UserDao{
@Autowired
protected RedisTemplate<Serializable, Serializable> redisTemplate;
public void saveUser(final User user) {
redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
redisTemplate.getStringSerializer().serialize(user.getName()));
return null;
}
});
}
public User getUser(final long id) {
return redisTemplate.execute(new RedisCallback<User>() {
public User doInRedis(RedisConnection connection) throws DataAccessException {
byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
if (connection.exists(key)) {
byte[] value = connection.get(key);
String name = redisTemplate.getStringSerializer().deserialize(value);
User user = new User();
user.setName(name);
user.setId(id);
return user;
}
return null;
}
});
}
}
spring配置文件:applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:redis.properties" />
<context:component-scan base-package="com.tgb.klx.redis">
</context:component-scan>
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxActive" value="${redis.maxActive}" />
<property name="maxWait" value="${redis.maxWait}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
<bean id="userDao" class="com.tgb.klx.redis.dao.impl.UserDaoImpl" />
</beans>
将redis交给spring容器管理,将redisTempate的bean注入到UserDaoImpl中,UserDaoImpl即可使用redisTemplate进行操作,但是看UserDaoImpl的实现,我们会发现很麻烦,重复的代码很多,那么下一步进行优化。
第二种方法:
目录结构如下
spring的配置文件如下:
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:redis.properties" />
<context:component-scan base-package="com.tgb.klx.redis">
</context:component-scan>
<context:component-scan base-package="com.tgb.klx.redis.test">
</context:component-scan>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxActive" value="50" />
<property name="maxIdle" value="8" />
<property name="maxWait" value="1000" />
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<!-- <property name="testWhileIdle" value="true"/> -->
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton">
<constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}" />
<constructor-arg name="port" value="${redis.port}" />
<constructor-arg name="timeout" value="${redis.timeout}" />
<constructor-arg name="weight" value="1" />
</bean>
</list>
</constructor-arg>
</bean>
</beans>
将jedisPoolConfig和shardedJedisPool交给spring容器管理。
RedisDataSourceImpl.java代码
@Repository("redisDataSource")
public class RedisDataSourceImpl implements RedisDataSource {
private static final Logger log = LoggerFactory.getLogger(RedisDataSourceImpl.class);
@Autowired
private ShardedJedisPool shardedJedisPool;
public ShardedJedis getRedisClient() {
try {
ShardedJedis shardJedis = shardedJedisPool.getResource();
return shardJedis;
} catch (Exception e) {
log.error("getRedisClent error", e);
}
return null;
}
public void returnResource(ShardedJedis shardedJedis) {
shardedJedisPool.returnResource(shardedJedis);
}
public void returnResource(ShardedJedis shardedJedis, boolean broken) {
if (broken) {
shardedJedisPool.returnBrokenResource(shardedJedis);
} else {
shardedJedisPool.returnResource(shardedJedis);
}
}
}
该类的主要作用是,通过shardedJedisPool获取shardJedis。shardedJedisPool在spring配置文件中已经配置。
RedisClientTemplate.java
@Repository("redisClientTemplate")
public class RedisClientTemplate {
private static final Logger log = LoggerFactory.getLogger(RedisClientTemplate.class);
@Autowired
private RedisDataSource redisDataSource;
public void disconnect() {
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
shardedJedis.disconnect();
}
/**
* 设置单个值
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.set(key, value);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
/**
* 获取单个值
*
* @param key
* @return
*/
public String get(String key) {
String result = null;
ShardedJedis shardedJedis = redisDataSource.getRedisClient();
if (shardedJedis == null) {
return result;
}
boolean broken = false;
try {
result = shardedJedis.get(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
broken = true;
} finally {
redisDataSource.returnResource(shardedJedis, broken);
}
return result;
}
该类通过redisDataSource获取到shardJedis,利用shardJedis中封装好的方法,进行保存、查询等。不用像第一种方法一样,每个dao层都需要封装自己的查询、保存方法。用此种方法只需要在spring中取redisClientTemplate的bean使用。
测试
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:config/data-source.xml");
RedisClientTemplate redisClient = (RedisClientTemplate)ac.getBean("redisClientTemplate");
redisClient.set("a", "abc");
System.out.println(redisClient.get("a"));
}
总结
redis的简单使用如上,redis是一款很优秀的缓存产品。Redis3.0版本发布后,实现了分布式的Redis即Redis Cluster,从而做到了对集群的支持,可以实现高可用方案。