SpringBoot+redis
1.导入依赖2.建立连接(测试类中,另外写一个测试方法)1.设置键和值1.取值3.关闭hash1.连接2.存储3.获取hash全部获取4.关闭lpush源码setjedis连接池1.创建一个配置对象2.创建连接池对象jedispool源码把池子配置进去,本机和端口3.得到Jedis获取连接设置数据获取4.关闭连接新建一个工
链接redis
1.导入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
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);
全部获取
Map<String, String> map = 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<String> 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<String> 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<String> 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 GenericObjectPoolConfig<Jedis> poolConfig, 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.导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
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<String,String> 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<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
通过源码可以看出,SpringBoot自动帮我们在容器中生成了一个RedisTemplate和一个StringRedisTemplate。但是,这个RedisTemplate的泛型是<Object,Object>,写代码不方便,需要写好多类型转换的代码;我们需要一个泛型为<String,Object>形式的RedisTemplate。并且,这个RedisTemplate没有设置数据存在Redis时,key及value的序列化方式。(每次都是自己手动序列化)
也就是说要自己写一个用自己的
看到这个@ConditionalOnMissingBean注解后,就知道如果Spring容器中有了RedisTemplate对象了,这个自动配置的RedisTemplate不会实例化。因此我们可以直接自己写个配置类,配置RedisTemplate。
7.创建配置类config
加上注解 :@Configuration //redis配置类
@Configuration //redis配置类
public class RedisConfig {
//固定模板
@Bean //注入进去
@SuppressWarnings("all") //可以不加,镇压的注解,因为內部的某些警告,一些成员属性会被爆红,但它又不是报错,所以要让它保持静默
public RedisTemplate<String,Object>redisTemplate(RedisConnectionFactory factory){
//创建RedisTemplate
RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
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<String,Object> redisTemplate;
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
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;
}
}
/**
* 根据 key 获取过期时间
*
* @param key 键(不能为 Null)
* @return 时间(秒) 返回0代表永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断 key 是否存在
*
* @param key 键(不能为 Null)
* @return true 存在 false 不存在
*/
public boolean hashKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
public void del(String... key) {
if (key != null && key.length > 0) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
//==================================String====================================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true 成功 false 失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time > 0 若 time <= 0 将设置无限期
* @return true 成功 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;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().decrement(key, delta);
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
*/
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;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
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;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
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=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
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;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
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=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 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;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 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;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
*/
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"));
}
更多推荐
所有评论(0)