1.下载redis服务器端程序;
在redis.io官网完成服务器端程序下载;可下载安装版或解压版,此处我下载的是解压版,下载完成后解压。
2.配置redis密码,开启redis服务端
在redis.windows.conf中搜索requirepass,找到#requirepass 行,在下面新建一行,设置自己的redis访问密码。
此处我们配置密码为“redis”
requirepass redis
然后CMD进入解压后的目录。开启redis服务端:
3.新建maven quick start项目,导入redis依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>RedisDemo</groupId> <artifactId>RedisTest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Test</name> <description>no</description> <dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.2</version> </dependency> </dependencies> </project>
4.新建user类
public class User { private String id; private String name; private String sex; private int age; public User(String id, String name, int age, String sex) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]"; } }
5.新建测试类
import java.util.HashMap; import java.util.Map; import java.util.UUID; import com.alibaba.fastjson.JSON; import redis.clients.jedis.Jedis; public class Main { public static void main(String[] args) { //1.获取jedis对象 Jedis jedis = new Jedis("127.0.0.1",6379); //密码验证 jedis.auth("redis"); //创建5个user对象并初始化 User u1 = new User("ADC","uzi",20,"m"); User u2 = new User("APC","faker",24,"m"); User u3 = new User("JUG","clearlove",25,"m"); User u4 = new User("TOP","ss17",22,"m"); User u5 = new User("SUP","baolan",24,"m"); //创建HashMap用于在redis中储存多个user Map<String,String> userMap = new HashMap<>(); //HashMap填充 userMap.put("RNG", JSON.toJSONString(u1)); userMap.put("SKT", JSON.toJSONString(u2)); userMap.put("EDG", JSON.toJSONString(u3)); userMap.put("LGD", JSON.toJSONString(u4)); userMap.put("IG", JSON.toJSONString(u5)); //使用redis的hmset指令来完成储存 jedis.hmset("Users",userMap); System.out.println(jedis.hget("Users","RNG")); } }
执行后控制台可以看到会打印 以下信息
{"age":20,"id":"ADC","name":"uzi","sex":"m"}
6.在服务端查看储存结果