1.首先添加Redis依赖
<!-- Redis依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2.创建实体类
public class User {
private String uid;
private String userName;
private String password;
private String name;
//todo get、set、toString、有参、无参构造方法
3.创建Dao层
public class UserDao {
//声明一个jedis
private static Jedis jedis;
/**
* 添加一个有参构造方法
*/
public UserDao(Jedis jedis){
this.jedis=jedis;
}
/**
* 添加
*/
public void addUser(User user){
//首先保存user-id
jedis.sadd("useradd","user-"+user.getUid());
//添加数据
Map<String,String>map=new HashMap<>();
map.put("uid",user.getUid());
map.put("userName",user.getUserName());
map.put("password",user.getPassword());
map.put("name",user.getName());
jedis.hmset("user-"+user.getUid(),map);
}
/**
* 获取单个User
*/
public List<String> getUserById(String id){
if(exists()){
return jedis.hmget("user-"+id,"id","userName","password","name");
}
return null;
}
/**
* 获取全部
*/
public List<User>getUserAll(){
List<User>userList=new ArrayList<>();
User user=null;
if (exists()){
for (String useradd:jedis.smembers("useradd")) {
user=new User();
List<String>lists=jedis.hmget(useradd,"id","userName","password","name");
user.setUid(lists.get(0));
user.setUserName(lists.get(1));
user.setPassword(lists.get(2));
user.setName(lists.get(3));
userList.add(user);
}
return userList;
}
return null;
}
/**
* 删除全部
*/
public boolean deleteAll(){
if(exists()){
jedis.del("useradd");
return true;
}
return false;
}
/**
* 判断是否存在
*/
public boolean exists(){
return jedis.exists("useradd");
}
}
4.创建测试类
public class UserTest {
private static Jedis jedis=null;
public static void main(String[] args) {
//连接本地Redis服务
jedis=new Jedis("localhost");
System.out.println("连接成功!");
//查看服务是否正常运行
System.out.println("服务正在运行"+jedis.ping());
user();
}
public static void user(){
UserDao userDao=new UserDao(jedis);
userDao.deleteAll();
userDao.addUser(new User("1","1班","123","张三"));
userDao.addUser(new User("2","2班","456","李四"));
userDao.addUser(new User("3","1班","789","王五"));
userDao.addUser(new User("4","3班","147","老六"));
for (User user:userDao.getUserAll()){
System.out.println(user);
}
}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/RHHcainiao/article/details/117526747