1. 程式人生 > 其它 >java connect redis by jedis

java connect redis by jedis

package org.stock;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

import redis.clients.jedis.Jedis;

class User {
public User(String name,Integer age, Date birthDay) {
this.name = name;
this.age = age;
this.birthDay = birthDay;
}
private String name;
private Integer age;

@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date birthDay;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
}


public class JedisUtil {
public static void main(String[] args) {
JedisUtil app = new JedisUtil();
Jedis jedis = JedisUtil.connect("localhost", "123456");
System.out.println("i am ok~");
jedis.set("x", "測試資料");
System.out.println("redis 儲存的字串為: "+ jedis.get("x"));

jedis.lpush("site-list", "Google");
jedis.lpush("site-list", "Taobao");
// 獲取儲存的資料並輸出
List<String> list = jedis.lrange("site-list", 0 ,2);
for(int i=0; i<list.size(); i++) {
System.out.println("列表項為: "+list.get(i));
}

Set<String> keys = jedis.keys("*");
Iterator<String> it=keys.iterator() ;
while(it.hasNext()){
String key = it.next();
System.out.println(key);
}

User user = new User("好好", 12, new Date());
System.out.println(JSON.toJSONString(user));

jedis.close();
}

@SuppressWarnings("deprecation")
public static Jedis connect(String host, String password) {
Jedis jedis = new Jedis(host);
jedis.auth(password);
return jedis;
}
}