1.导入依赖
redis.clients jedis
2.建立连接(测试类中,另外写一个测试方法)
Jedis jedis = new Jedis("localhost",6379);
操作数据结构 String
1.设置键和值
jedis.set("username","lxyk");
1.取值
System.out.println(jedis.get("username"));
3.关闭
jedis.close();
hash
1.连接
Jedis jedis = new Jedis();//如果使用空参构造,默认值就是localhost 6379
2.存储
jedis.hset("aaaa","name","fbb");
jedis.hset("aaaa","age","23");
jedis.hset("aaaa","gender","male");
3.获取hash
String hget = jedis.hget("aaaa", "name");
System.out.println(hget);
全部获取
Mapmap = jedis.hgetAll("aaaa"); //全部获取 for (String key : map.keySet()) { String value = map.get(key); System.out.println(key + ":"+value); }
4.关闭
jedis.close();list
@Test
public void test4(){
Jedis jedis = new Jedis();
//存储
jedis.lpush("myList","a","b","c"); //左边存 lpush方法中value的位置是可变参数
jedis.rpush("myList","a","b","c"); //右边存
//获取
List myList = jedis.lrange("myList", 0, -1);
System.out.println("myList = " + myList);
//list弹出
System.out.println(jedis.lpop("myList")); //左弹出
System.out.println(jedis.rpop("myList")); //右弹出
//获取
List myList2 = jedis.lrange("myList", 0, -1);
System.out.println("myList2 = " + myList2);
jedis.close();
}
lpush源码
@Override
public Long lpush(final String key, final String... strings) {
checkIsInMultiOrPipeline();
client.lpush(key, strings);
return client.getIntegerReply();
}
set
//set
@Test
public void test5(){
Jedis jedis = new Jedis();
//set存储
jedis.sadd("myset","java","php","C++","Go");
//set获取
Set myset = jedis.smembers("myset");
System.out.println("myset = " + myset);
jedis.close();
}
jedis连接池
1.创建一个配置对象
JedisPoolConfig config = new JedisPoolConfig(); //Jedis 池配置
config.setMaxTotal(50); //最大连接数
config.setMaxIdle(10); //最大空闲连接
2.创建连接池对象
JedisPool jedisPool = new JedisPool(config,"localhost",6379);
jedispool源码
public JedisPool(final GenericObjectPoolConfigpoolConfig, final String host, final int port) { this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT); }
把池子配置进去,本机和端口
3.得到Jedis获取连接
Jedis resource = jedisPool.getResource(); //获取资源
设置数据
resource.set("hehe","fbbb");
获取
System.out.println(resource.get("hehe"));
4.关闭连接
resource.close();
工具类操作
新建一个工具包utils
创建一个工具类
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//工具类
public class JedisPoolUtils {
//1.来个静态成员变量
private static JedisPool jedisPool;
static {
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader()
.getResourceAsStream("jedis.properties"); //需要写一个配置文件
//创建
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig(); //Jedis 池配置
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle"))); //为什么都是这个方法
jedisPool =
new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
}
//获取连接的方法
public static Jedis getJedis() {
return jedisPool.getResource(); //== Jedis resource = jedisPool.getResource(); //获取资源
}
}
其中静态代码块中的
//读取配置文件
InputStream is = JedisPoolUtils.class.getClassLoader()
.getResourceAsStream("jedis.properties"); //需要写一个配置文件
//创建
Properties pro = new Properties();
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig(); //Jedis 池配置
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
host=127.0.0.1 port=6379 maxTotal=50 maxIdle=10
对应着jedis连接池方法中的
//创建一个配置对象
JedisPoolConfig config = new JedisPoolConfig(); //Jedis 池配置
config.setMaxTotal(50); //最大连接数
config.setMaxIdle(10); //最大空闲连接
jedisPool =
new JedisPool(config,pro.getProperty("host"),Integer.parseInt(pro.getProperty("port")));
对应着
JedisPool jedisPool = new JedisPool(config,"localhost",6379);
最后返回方法
//获取连接的方法
public static Jedis getJedis(){
return jedisPool.getResource();
}
对应
Jedis resource = jedisPool.getResource(); //获取资源
测试方法
//工具类操作
@Test
public void test8(){
//通过工具类连接
Jedis jedis = JedisPoolUtils.getJedis();
//设置数据
jedis.set("hello","world");
//关闭连接
jedis.close();
}
SpringBoot整合redis
1.导入依赖
org.springframework.boot spring-boot-starter-data-redis
2.配置yml文件
server:
port: 8080
spring:
application:
name: springboot-redis
redis:
host: 127.0.0.1 #主机ip
port: 6379 #端口
3.测试类中加入
@Autowired private RedisTemplate redisTemplate;
加入了第一步注解后就会有RedisTemplate
4.可以存值了
@Test
void contextLoads() {
redisTemplate.boundValueOps("xxxxx").set("fbb"); //绑定值操作
}
取值
@Test
public void test(){
Object name = redisTemplate.boundValueOps("xxxxx").get();
System.out.println(name);
}
5.测试没问题后,可以取写controller
在写controller之前想想要返回什么东西?返回什么写什么的注解 如:
@RestController
然后注入redisTemplate
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/redis")
public String redis(){
redisTemplate.opsForValue().set("password","www.baidu.com"); //opsForValue:操作字符串
System.out.println(redisTemplate.opsForValue().get("password"));
return "success";
}
* 操作字符串:opsForValue() * 操作list:opsForList() * 操作set:opsForSet() * 操作hash:opsForHash() * 操作sortdset:opsForZSet()
然后运行即可
6.写实体类(加入lombok)
实现实体类的序列化,不然会报错(Serializable)
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component //注入到容器中
public class User implements Serializable { //实现实体类的序列化,不然会报错
private int id;
private String name;
}
Redis Template的自动配置
源码
@Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate
通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是
也就是说要自己写一个用自己的
看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。
7.创建配置类config
加上注解 :@Configuration //redis配置类
@Configuration //redis配置类
public class RedisConfig {
//固定模板
@Bean //注入进去
@SuppressWarnings("all") //可以不加,镇压的注解,因为內部的某些警告,一些成员属性会被爆红,但它又不是报错,所以要让它保持静默
public RedisTemplateredisTemplate(RedisConnectionFactory factory){
//创建RedisTemplate
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
//json序列化配置
Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //序列化的是值,所以Object
//处理json串的
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jsonRedisSerializer.setObjectMapper(mapper);
//string序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用string的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key采用string的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化采用json序列化配置
template.setValueSerializer(jsonRedisSerializer); //json序列化配置
template.afterPropertiesSet();
return template;
}
}
8.最后写工具类(不用写,复制)
package com.lxyk.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hashKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void del(String... key) {
if (key != null && key.length > 0) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
}
}
//==================================String====================================
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().decrement(key, delta);
}
// ===============================list=================================
public List lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ============================set=============================
public Set sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ================================Map=================================
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ===============================HyperLogLog=================================
public long pfadd(String key, String value) {
return redisTemplate.opsForHyperLogLog().add(key, value);
}
public long pfcount(String key) {
return redisTemplate.opsForHyperLogLog().size(key);
}
public void pfremove(String key) {
redisTemplate.opsForHyperLogLog().delete(key);
}
public void pfmerge(String key1, String key2) {
redisTemplate.opsForHyperLogLog().union(key1, key2);
}
}
最后取测试是否可以使用(在测试类中测试)
注入我们的工具类
@Autowired
private RedisUtil redisUtil;
测试方法
@Test
public void test3(){
redisUtil.set("names","fbb");
System.out.println(redisUtil.get("names"));
}



