spring boot 整合 redis
需要的工具,环境:
jdk1.8,idea
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--lettuce pool 缓存连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
User
public class User {
private Integer id;
private String userName;
private String sex;
public User() {
}
public User(Integer id, String userName, String sex) {
this.id = id;
this.userName = userName;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
RedesTemplate
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
@Configuration
public class RedesTemplate {
@Bean
public RedisTemplate<String,Serializable> redisTemplate(LettuceConnectionFactory connectionFactory){
RedisTemplate<String,Serializable> template=new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(connectionFactory);
return template;
}
}
RedisOperateControl
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
@Controller
public class RedisOperateControl {
@Resource
private RedisTemplate template;
@RequestMapping("add")
public void add(){
User user=new User(1,"java 的架构师技术栈","man");
ValueOperations<String,User> operations=template.opsForValue();
operations.set("user1",user);
boolean exists=template.hasKey("user1");
System.out.println("redis 是否存在相应 key"+exists);
User user1= (User) template.opsForValue().get("user1");
System.out.println(JSON.toJSONString(user1));
ListOperations<String,User> operationslist=template.opsForList();
}
}