redis简介及其基本操作,java访问redis
Redis
- Redis 是采用 C 语言编写,内存数据存储。
- Redis 读写速度异常快速,适合做应用缓存
- Redis 支持字符串、哈希、列表、集合、有序集合结构存储
- Redis 支持持久化操作(RDB 和 AOF 机制)
- Redis 可以和 Java、PHP、Python 等语言结合访问
Redis 操作命令
字符串操作 (string)
- set key value // 设置一组 key value
- get key // 获取 value 值
- mset key value key value // 设置多组 key value
- strlen key // 查看 value 字符数量
- incr key // 将 value 值加 1
- incrby key n // 将 value 值加 n
- decr key // 将 value 值减 1
- decrby key n // 将 value 值减 n
- append key value // 字符串拼接
key 操作
- keys * // 查看所有 key
- del key // 删除 key
- type key // 查看 value 类型
- expire key n // 指定失效时间(秒)
哈希操作 (hash)
- hset key field value // 设置一组字段名和字段值
- hmset key field1 value1 field2 value2... // 设置多组字段名和字段值
- hget key field // 获取字段值
- hmget key field1 field2 // 获取多个字段值
- hkeys key // 查看哈希包含的字段名
- hlen key // 查看哈希包含的字段数量
- hdel key field // 删除哈希中的某个字段
列表操作 (list)
- lpush key value // 向列表头部插入一个元素
- rpush key value // 向列表尾部插入一个元素
- llen key // 列表元素数量
- lrange key 0 -1 // 获取所有元素
- lpop // 弹出列表头部元素
集合操作
- sadd key member // 添加元素
- srem key member // 删除元素
- smembers key // 返回所有元素
- scard key // 返回集合元素数量
- srandmember key n // 随机返回 n 个
- sunion key1 key2 //key1 并 key2
- sinter key1 key2 //key1 交 key2
- sdiff key1 key2 //key1 差 key2
有序集合操作
- zadd key score member // 添加元素
- zcard key // 集合元素数量
- zrange key 0 -1 // 由小到大顺序查看所有元素
- zrevrange key 0 -1 // 由大到小顺序查看所有元素
- zcount key min max // 按分数统计元素数量
- zrem key memeber // 删除元素
Java 访问 Redis
基于 jedis.jar 访问
@Test
public void test1(){
Jedis jedis = new Jedis("localhost", 6379);
System.out.println(jedis.ping());
Set<String> keys = jedis.keys("*");//keys *
for(String key:keys){
System.out.println(key+":"+jedis.type(key));
}
jedis.close();
}
@Test
public void test2(){
Jedis jedis = new Jedis("localhost", 6379);
// 取 string
String value1 = jedis.get("name");//get name
System.out.println("name="+value1);
// 取 hash
String value2 = jedis.hget("dept10", "dname");//hget dept10 dname
System.out.println("dname="+value2);
// 获取 hash 所有字段值
Set<String> fields = jedis.hkeys("dept20");
for(String f:fields){
System.out.println(f+":"+jedis.hget("dept20", f));
}
jedis.close();
}
@Test
public void test3(){
<span class="hljs-title class_">Map</span><<span class="hljs-title class_">String</span>, <span class="hljs-title class_">String</span>> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span><>();
data.<span class="hljs-title function_">put</span>(<span class="hljs-string">"no"</span>, <span class="hljs-string">"101"</span>);
data.<span class="hljs-title function_">put</span>(<span class="hljs-string">"name"</span>, <span class="hljs-string">"tom"</span>);
<span class="hljs-title class_">Jedis</span> jedis = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Jedis</span>(<span class="hljs-string">"localhost"</span>, <span class="hljs-number">6379</span>);
jedis.<span class="hljs-title function_">hmset</span>(<span class="hljs-string">"mymap1"</span>, data);<span class="hljs-comment">//存入map</span>
<span class="hljs-title class_">Map</span><<span class="hljs-title class_">String</span>,<span class="hljs-title class_">String</span>> map = jedis.<span class="hljs-title function_">hgetAll</span>(<span class="hljs-string">"mymap1"</span>);<span class="hljs-comment">//获取map</span>
<span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(map.<span class="hljs-title function_">get</span>(<span class="hljs-string">"no"</span>)+<span class="hljs-string">" "</span>+map.<span class="hljs-title function_">get</span>(<span class="hljs-string">"name"</span>));
jedis.<span class="hljs-title function_">close</span>();
}
@Test
public void test4(){
Dept dept = new Dept();
dept.setDeptno(10);
dept.setDname("Java");
dept.setLoc("北京");
<span class="hljs-title class_">Jedis</span> jedis = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Jedis</span>(<span class="hljs-string">"localhost"</span>, <span class="hljs-number">6379</span>);
jedis.<span class="hljs-title function_">set</span>(<span class="hljs-string">"dept"</span>.<span class="hljs-title function_">getBytes</span>(), <span class="hljs-title class_">SerializableUtil</span>.<span class="hljs-title function_">objectToBytes</span>(dept));
jedis.<span class="hljs-title function_">close</span>();
}
@Test
public void test5(){
Jedis jedis = new Jedis("localhost", 6379);
byte[] bytes = jedis.get("dept".getBytes());
Dept dept = (Dept)SerializableUtil.bytesToObject(bytes);
System.out.println(dept.getDeptno()+" "+dept.getDname()+" "+dept.getLoc());
jedis.close();
}
SerializableUtil.java
public class SerializableUtil {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Object <span class="hljs-title">bytesToObject</span>(<span class="hljs-params"><span class="hljs-built_in">byte</span>[] bytes</span>)</span>{
ByteArrayInputStream input = <span class="hljs-literal">null</span>;
ObjectInputStream ois = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">try</span>{
input = <span class="hljs-keyword">new</span> ByteArrayInputStream(bytes);
ois = <span class="hljs-keyword">new</span> ObjectInputStream(input);
Object obj = ois.readObject();<span class="hljs-comment">//反序列化将字节数组转成Object</span>
<span class="hljs-keyword">return</span> obj;
}<span class="hljs-keyword">catch</span>(Exception ex){
ex.printStackTrace();
<span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
}<span class="hljs-keyword">finally</span>{
<span class="hljs-keyword">try</span> {
input.close();
} <span class="hljs-keyword">catch</span> (IOException e) {
e.printStackTrace();
}
<span class="hljs-keyword">try</span> {
ois.close();
} <span class="hljs-keyword">catch</span> (IOException e) {
e.printStackTrace();
}
}
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-built_in">byte</span>[] <span class="hljs-title">objectToBytes</span>(<span class="hljs-params">Object obj</span>)</span>{
ByteArrayOutputStream <span class="hljs-keyword">out</span> = <span class="hljs-literal">null</span>;
ObjectOutputStream oos = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">try</span>{
<span class="hljs-keyword">out</span> = <span class="hljs-keyword">new</span> ByteArrayOutputStream();
oos = <span class="hljs-keyword">new</span> ObjectOutputStream(<span class="hljs-keyword">out</span>);
oos.writeObject(obj);<span class="hljs-comment">//将obj序列化后写入out对象中</span>
<span class="hljs-built_in">byte</span>[] bytes = <span class="hljs-keyword">out</span>.toByteArray();
<span class="hljs-keyword">return</span> bytes;
}<span class="hljs-keyword">catch</span>(Exception e){
e.printStackTrace();
<span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
}<span class="hljs-keyword">finally</span>{
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">out</span>.close();
} <span class="hljs-keyword">catch</span> (IOException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
<span class="hljs-keyword">try</span> {
oos.close();
} <span class="hljs-keyword">catch</span> (IOException e) {
<span class="hljs-comment">// TODO Auto-generated catch block</span>
e.printStackTrace();
}
}
}
}
基于 SpringData-redis 访问
-
引入 spring-data-redis 包、jedis、connection-pool 包
-
在 Spring 配置文件定义 RedisTemplate、JedisConnectionFactory 组件
<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="localhost"> </property> <property name="port" value="6379"></property> </bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisConnectionFactory">
</property>
</bean> -
注入 RedisTemplate 测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class TestRedisTemplate {
<span class="hljs-meta">@Autowired</span> <span class="hljs-keyword">private</span> <span class="hljs-title class_">RedisTemplate</span><<span class="hljs-title class_">Object</span>,<span class="hljs-title class_">Object</span>> redisTemplate; <span class="hljs-meta">@Test</span> <span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">test1</span>(<span class="hljs-params"></span>){ redisTemplate.<span class="hljs-title function_">opsForValue</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">"name"</span>, <span class="hljs-string">"XDL"</span>); <span class="hljs-title class_">String</span> value = (<span class="hljs-title class_">String</span>)redisTemplate.<span class="hljs-title function_">opsForValue</span>().<span class="hljs-title function_">get</span>(<span class="hljs-string">"name"</span>); <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(value); } <span class="hljs-meta">@Test</span> <span class="hljs-keyword">public</span> <span class="hljs-built_in">void</span> <span class="hljs-title function_">test2</span>(<span class="hljs-params"></span>){ <span class="hljs-title class_">Dept</span> dept = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Dept</span>(); dept.<span class="hljs-title function_">setDeptno</span>(<span class="hljs-number">20</span>); dept.<span class="hljs-title function_">setDname</span>(<span class="hljs-string">"XDL"</span>); dept.<span class="hljs-title function_">setLoc</span>(<span class="hljs-string">"北京"</span>); redisTemplate.<span class="hljs-title function_">opsForValue</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">"dept"</span>, dept); <span class="hljs-title class_">Dept</span> d = (<span class="hljs-title class_">Dept</span>)redisTemplate.<span class="hljs-title function_">opsForValue</span>().<span class="hljs-title function_">get</span>(<span class="hljs-string">"dept"</span>); <span class="hljs-title class_">System</span>.<span class="hljs-property">out</span>.<span class="hljs-title function_">println</span>(d.<span class="hljs-title function_">getDeptno</span>()+<span class="hljs-string">" "</span>+d.<span class="hljs-title function_">getDname</span>()+<span class="hljs-string">" "</span>+d.<span class="hljs-title function_">getLoc</span>()); }
}
Redis 缓存使用
@Resource
private RedisTemplate<Object, Object> redisTemplate;
@RequestMapping(value="/dept/get",method=RequestMethod.GET)
public Dept loadDept(@RequestParam("no")int id){
// 查找 Redis 缓存,有返回
Dept dept = (Dept)redisTemplate.opsForValue().get("dept:"+id);
//Redis 没有,调用 deptDao 查询数据库,并将结果放入缓存
if(dept == null){
System.out.println("从数据库查询加载数据");
dept = deptDao.findById(id);
redisTemplate.opsForValue().set("dept:"+id, dept);
}else{
System.out.println("从 Redis 缓存查询加载数据");
}
return dept;
}