谁有关于redis 存储海量数据高性能的demo,请上传一下

2025-04-08 13:36:30
推荐回答(1个)
回答1:

1. Redis使用场景

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

我们都知道,在日常的应用中,数据库瓶颈是最容易出现的。数据量太大和频繁的查询,由于磁盘IO性能的局限性,导致项目的性能越来越低。

这时候,基于内存的缓存框架,就能解决我们很多问题。例如Memcache,Redis等。将一些频繁使用的数据放入缓存读取,大大降低了数据库的负担。提升了系统的性能。

其实,对于hibernate的二级缓存,是同样的道理。利用内存高速的读写速度,来解决硬盘的瓶颈。

2. 配置使用redis

首先,我们需要引入基本的jar包。maven中的基本引用如下:

    
org.springframework.data
spring-data-redis
1.4.2.RELEASE



redis.clients
jedis
2.6.2


然后,在applicationContext中配置如下:








p:pool-config-ref="poolConfig" />








对于hibernate的配置可知,第一个poolconfig是对连接池的配置。包括最大连接数,队列数,存活时间,最大等待时间等等,还有一些额外的配置,请直接点击JedisPoolConfig类源码,进行查看。

这些配置的意思如果不明白的话,一定要去把线程池好好学习下。

第一个配置是连接工厂,顾名思义,最基本的使用一定是对连接的打开和关闭。我们需要为其配置redis服务器的账户密码,端口号。(这里还可以配置数据库的index,但是我使用时候一直使用redis的默认数据库,也就是第0个)

最后一个配置特别重要。这个类似于spring提供的HibernateDaoSupport。

接下来,全部讲解都将围绕这个类展开。

3. RedisTemplate的使用

这个类作为一个模版类,提供了很多快速使用redis的api,而不需要自己来维护连接,事务。

最初的时候,我创建的BaseRedisDao是继承自这个类的。继承的好处是我的每个Dao中,都可以自由的控制序列化器,自由的控制自己是否需要事务,这个先不需要了解,跟着我目前的这种配置方法来即可。

template提供了一系列的operation,比如valueOperation,HashOperation,ListOperation,SetOperation等,用来操作不同数据类型的Redis。

并且,RedisTemplate还提供了对应的*OperationsEditor,用来通过RedisTemplate直接注入对应的Operation。我们暂时不讲这个。

对于下面的test1方法,我们暂时不用考虑,先了解通过RedisTemplate来使用connection操作Redis。

Test代码如下:

package cn.test.spjedis;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cn.redis2.dao.IncrDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestRedis {
@Resource(name = "redisTemplate")
private RedisTemplate template; // inject the template as ListOperations
//至于这个为什么可以注入。需要参考AbstractBeanFactory doGetBean
//super.setValue(((RedisOperations) value).opsForValue());就这一行代码 依靠一个editor
@Resource(name = "redisTemplate")
private ValueOperations vOps;

public void testSet(){
template.execute(new RedisCallback() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
byte [] key = "tempkey".getBytes();
byte[] value = "tempvalue".getBytes();
connection.set(key, value);
return true;
}
});
}

public void testSet1(){
vOps.set("tempkey", "tempvalue");
}

@Autowired
private IncrDao incr;

@Test
public void addLink() {
System.out.println(incr.incr(13));
System.out.println(incr.get(13));
}

}