SpringBoot整合Redis
SpringBoot 操作数据:spring-data jpa jdbc mongodb redis!
SpringData 也是和 SpringBoot 齐名的项目!
说明: 在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce?
jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接
池! 更像 BIO 模式
lettuce : 采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据
了,更像 NIO 模式
源码分析:
@Bean
@ConditionalOnMissingBean(name = "redistemplate") // 我们可以自己定义一个 redistemplate来替换这个默认的!
public Redistemplate<Object, Object> redistemplate(RedisConnectionFactory redisConnectionFactory) throws UnkNownHostException {
// 默认的 Redistemplate 没有过多的设置,redis 对象都是需要序列化!
// 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 <String, Object>
Redistemplate<Object, Object> template = new Redistemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean @ConditionalOnMissingBean
// 由于 String 是redis中最常使用的类型,所以说单独提出来了一 个bean!
public StringRedistemplate stringRedistemplate(RedisConnectionFactory redisConnectionFactory) throws UnkNownHostException {
StringRedistemplate template = new StringRedistemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
整合测试一下
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置连接
#配置redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
3、测试
@SpringBoottest
class RedisSpringbootApplicationTests {
@Autowired
private Redistemplate redistemplate;
@Test
void contextLoads() {
// redistempLate 操作不同的数据类型,api和我们的指令是一样的
// opsForValue 操作字符串类似String
// opsForList 操作List类似List
// opsForSet
// opsForHash
// opsForzSet
// opsForGeo
// opsForHyperLogLog
//获取redis连接对象
// RedisConnection connection = redistemplate.getConnectionFactory().getConnection();
// connection.flushDb();
// connection.flushAll();
redistemplate.opsForValue().set("mykey", "saxon");
System.out.println(redistemplate.opsForValue().get("mykey"));
}
@Test
void test2() throws JsonProcessingException {
//真实开发一般会用json来传递对象
User user = new User("中文", 3);
String jsonUser = new ObjectMapper().writeValueAsstring(user);
//传递的对象需要序列化,不然报错
redistemplate.opsForValue().set("user",user);
System.out.println(redistemplate.opsForValue().get("user"));
}
}
关于对象的保存必须序列化
User.java
@Data
@Component
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private String name;
private int age;
}
编写自己的Redistemplete
@Configuration
public class RedisConfig {
//编写我们自己的redistemplate 固定模板,拿来即用
@Bean
public Redistemplate<String, Object> redistemplate(RedisConnectionFactory factory) {
//我们为了自己开发方便,一般使用<String, Object>
Redistemplate<String, Object> template = new Redistemplate<>();
template.setConnectionFactory(factory);
//Json序列化配置
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setobjectMapper(om);
//string 的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用string的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也采用string的方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化采用jackson
template.setValueSerializer(serializer);
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
Redis工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @ClassName:RedisUtils
* @Description:Redis工具类
* @Versiion:1.0
*/
@Service
public class RedisUtils {
@Autowired
private Redistemplate redistemplate;
private static double size = Math.pow(2, 32);
/**
* 写入缓存
*
* @param key
* @param offset 位 8Bit=1Byte
* @return
*/
public boolean setBit(String key, long offset, boolean isShow) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redistemplate.opsForValue();
operations.setBit(key, offset, isShow);
result = true;
} catch (Exception e) {
e.printstacktrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param offset
* @return
*/
public boolean getBit(String key, long offset) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redistemplate.opsForValue();
result = operations.getBit(key, offset);
} catch (Exception e) {
e.printstacktrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redistemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printstacktrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redistemplate.opsForValue();
operations.set(key, value);
redistemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printstacktrace();
}
return result;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redistemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redistemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redistemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redistemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redistemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redistemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redistemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public void add(String key, Object value) {
Setoperations<String, Object> set = redistemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
*
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
Setoperations<String, Object> set = redistemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合获取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByscore(String key, double scoure, double scoure1) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
redistemplate.opsForValue();
return zset.rangeByscore(key, scoure, scoure1);
}
//第一次加载的时候将数据加载到redis中
public void saveDataToRedis(String name) {
double index = Math.abs(name.hashCode() % size);
long indexLong = new Double(index).longValue();
boolean availableusers = setBit("availableusers", indexLong, true);
}
//第一次加载的时候将数据加载到redis中
public boolean getDataToRedis(String name) {
double index = Math.abs(name.hashCode() % size);
long indexLong = new Double(index).longValue();
return getBit("availableusers", indexLong);
}
/**
* 有序集合获取排名
*
* @param key 集合名称
* @param value 值
*/
public Long zRank(String key, Object value) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
return zset.rank(key,value);
}
/**
* 有序集合获取排名
*
* @param key
*/
public Set<ZSetoperations.TypedTuple<Object>> zRankWithscore(String key, long start,long end) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
Set<ZSetoperations.TypedTuple<Object>> ret = zset.rangeWithscores(key,start,end);
return ret;
}
/**
* 有序集合添加
*
* @param key
* @param value
*/
public Double zSetscore(String key, Object value) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
return zset.score(key,value);
}
/**
* 有序集合添加分数
*
* @param key
* @param value
* @param scoure
*/
public void incrementscore(String key, Object value, double scoure) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
zset.incrementscore(key, value, scoure);
}
/**
* 有序集合获取排名
*
* @param key
*/
public Set<ZSetoperations.TypedTuple<Object>> reverseZRankWithscore(String key, long start,long end) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
Set<ZSetoperations.TypedTuple<Object>> ret = zset.reverseRangeByscoreWithscores(key,start,end);
return ret;
}
/**
* 有序集合获取排名
*
* @param key
*/
public Set<ZSetoperations.TypedTuple<Object>> reverseZRankWithRank(String key, long start, long end) {
ZSetoperations<String, Object> zset = redistemplate.opsForZSet();
Set<ZSetoperations.TypedTuple<Object>> ret = zset.reverseRangeWithscores(key, start, end);
return ret;
}
}
@Autowired
private RedisUtils redisUtils;
@Test
void test3(){
redisUtils.set("name","张三");
redisUtils.get("name");
System.out.println(redisUtils.get("name"));
}
所有的redis操作,其实对于java开发人员来说,十分的简单,更重要是要去理解redis的思想和每
一种数据结构的用处和作用场景!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。