万事第一步(导包):
<!-- Jedis 操作Redis的框架-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
第二步封装工具类:
package com.mhy.boot_plus.utils;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Map;
/**
* @author Feri
* @date 2021/12/30 14:01
* @description:TODO Java操作Redis
*/
public class JedisUtils {
private static Jedis jedis;
static {
//完成实例化,连接Redis服务器
jedis=new Jedis("120.27.133.194",6380);
jedis.auth("123");
}
//新增
/**
* String类型 新增*/
public static void addString(String key,String value,long seconds){
jedis.setex(key, seconds, value);
}
public static void addString(String key,String value){
jedis.set(key, value);
}
public static void addHash(String key,String field,String value){
jedis.hset(key, field, value);
}
public static void addHash(String key, Map<String,String> map){
jedis.hmset(key, map);
}
public static void addList(String key,String value){
jedis.lpush(key,value);
}
public static void addGeo(String key,double lon,double lat,String address){
jedis.geoadd(key, lon, lat, address);
}
//校验
public static boolean exists(String... keys){
return jedis.exists(keys)>0;
}
public static boolean existsHash(String key,String field){
return jedis.hexists(key, field);
}
//删除
public static void delKey(String key){
jedis.del(key);
}
public static void delHash(String key,String field){
jedis.hdel(key,field);
}
//geo操作
public static double geodist(String key,String address1,String address2){
return jedis.geodist(key, address1, address2, GeoUnit.M);
}
public static List<GeoRadiusResponse> georadius(String key, double lon, double lat, double radius){
return jedis.georadius(key,lon,lat,radius,GeoUnit.M);
}
//系统命令
public static void expire(String key,long seconds){
jedis.expire(key, seconds);
}
public static long ttl(String key){
return jedis.ttl(key);
}
public static void main(String[] args) {
//String类型
jedis.set("str2112","Hello Word");//新增或修改
System.err.println(jedis.get("str2112"));//获取
System.err.println(jedis.strlen("str2112"));//长度
//List类型
jedis.lpush("list2112","1","2","3");
jedis.rpush("list2112","a","b","c");
//321abc
System.err.println(jedis.lrange("list2112",0,jedis.llen("list2112")-1));
System.err.println(jedis.lpop("list2112"));
System.err.println(jedis.rpop("list2112"));
//Hash类型
jedis.hset("hash2112","1","www");
System.err.println(jedis.hget("hash2112","1"));
System.err.println(jedis.hexists("hash2112","1"));
//Set类型
jedis.sadd("set2112","w","e","r");
System.err.println(jedis.smembers("set2112"));
System.err.println(jedis.sismember("set2112","w"));
}
}