序列化
package com.kuang.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.codec.cbor.Jackson2CborDecoder;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
// 编写自己的redisTemplate
@Bean
@SuppressWarnings("all")
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory)
throws UnknownHostException {
// 为了方便,一般直接使用String Object
RedisTemplate<String,Object> template = new RedisTemplate<String,Object>();
template.setConnectionFactory(factory);
// Jason序列化配置
Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectJackson2JsonRedisSerializer.setObjectMapper(om);
// String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化
template.setKeySerializer(stringRedisSerializer);
// Hash 的key采用
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(objectJackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
template.afterPropertiesSet();
// 配置具体的序列化方式
return template;
}
}
二、自己定义RedisUtil(只给出了部分)
自己设置一些方法,可以供redisUtil使用
package com.kuang.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.Map;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String,Object> 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);
}
// 判断KEY是否存在
public boolean hasKey(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){
if(key.length == 1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(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().increment(key,-delta);
}
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key,item);
}
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
}
测试:
package com.kuang;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuang.pojo.User;
import com.kuang.utils.RedisUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class Redis02SpringbootApplicationTests {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
@Autowired
private RedisUtil redisUtil;
@Test
public void test1(){
redisUtil.set("vivi",9);
//redisUtil.incr("vivi",10);
System.out.println(redisUtil.incr("vivi",9));
}
@Test
void contextLoads() {
// redisTemplate 操作不同的数据类型,api和我们的指令是一样的
// opsForValue
// opsForList
// opsForSet
// opsForHash
// opsForZSet
// opsForGeo
// 除了进本的操作,我们常用的方法都可以直接redisTemplate操作,比如事务、和基本的CRUD
// 获取Redis的连接对象
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
connection.flushDb();
connection.flushAll();
redisTemplate.opsForValue().set("key", "java");
System.out.println(redisTemplate.opsForValue().get("key"));
}
@Test
public void test() throws JsonProcessingException {
// 真实的开发一般都使用json来传递对象
User user = new User("狂神说",3);
String jsonUser = new ObjectMapper().writeValueAsString(user);
redisTemplate.opsForValue().set("user",jsonUser);
System.out.println(redisTemplate.opsForValue().get("user"));
}
}