在创建springboot的时候
勾选NOSQL中的redis
编写application.properties
spring.redis.host=你的地址
spring.redis.password=你的密码
创建util包
package com.redis.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisUtils {
@Autowired
private StringRedisTemplate redisTemplate;
public void set(String key,String value){
redisTemplate.opsForValue().set(key,value);
}
public String get(String key){
return redisTemplate.opsForValue().get(key);
}
public void hset(String key,String field,Object value){
redisTemplate.opsForHash().put(key,field,value);
}
public Object hget(String key,String field){
return redisTemplate.opsForHash().get(key,field);
}
}
在test测试里面
package com.redis;
import com.redis.util.RedisUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RedisApplicationTests {
@Autowired
RedisUtils redisUtils;
/**
* 测试存入
*/
@Test
void contextLoads() {
redisUtils.set("msg","hello");
String msg=redisUtils.get("msg");
System.out.println(msg);
}
}
序列化
package com.money.lin.util;
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;
@Configuration
public class RedisUtil {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
//指定键值
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
return redisTemplate;
}
}