springboot中不通过注解连接redis
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashSet;
import java.util.Set;
/**
* @author lc
* @version 1.0
* @description: TODO
* @date 2023/10/31 15:32
*/
@RunWith(SpringRunner.class)
public class RedisTest {
@Test
public void testSet(){
LettuceConnectionFactory conn = new LettuceConnectionFactory();
conn.setDatabase(0);
conn.setHostName("127.0.0.1");
conn.setPort(6379);
conn.setPassword("a@123");
//conn.setUsePool(true);
conn.afterPropertiesSet();
RedisTemplate<String,Object> template = new RedisTemplate<>();
template.setConnectionFactory(conn);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJlZDZiOTM2Zi1kNjY0LTRiYzEtOWFmZC1hZmY0N2NjZTEyZjAiLCJpYXQiOjE2OTg3MzI2NjUsInN1YiI6InNiZHMiLCJpc3MiOiJ3d3cuZ2Vvc2NlbmUuY24iLCJleHAiOjE3MDEzMjQ2NjV9.iWOhmHJZf8ktCrGGTw6eUACGuMTjDLrGzSlnSCrV0S8";
Object newvalue1= template.opsForValue().get(token);
String key="testkey";
String value = "testvalue";
template.opsForValue().set(key, value);
String newvalue = (String) template.opsForValue().get(key);
assert value.equalsIgnoreCase(newvalue);
}
}
网友评论