springboot整合redis单机版
数据库表结构
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`address` varchar(255) DEFAULT NULL,
`brithday` datetime DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('2', '河南信阳', '2018-07-06 14:54:30', '张三', '男');
INSERT INTO `t_user` VALUES ('3', '河南信阳', '2018-07-06 11:14:53', '小美', '女');
pom
<!-- 使用springmvc和spring的jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot整合mybatis,注解版 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
#redis单服务器配置
spring.redis.database=0
spring.redis.host=192.168.163.128
spring.redis.port=6379
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=1000
RedisSingleConfiguration.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisSingleConfiguration extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.database}")
private int database;
//如果redis设置密码了可以添加这个参数
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
//如果redis设置了密码
//JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
}
注:"RedisSingleConfiguration"是redis单机版的一个配置类,其作用就是可以注入"JedisPool"这个jedis连接池,所有"JedisPool"可以按照自己的逻辑设置redis的"key"值。
启动类
@SpringBootApplication(scanBasePackages="com.yunxiang")
@MapperScan("com.yunxiang.mapper")
//开启缓存
@EnableCaching
public class SpringApplications {
public static void main(String[] args) {
SpringApplication.run(SpringApplications.class, args);
}
}
UserMapper.java
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.yunxiang.pojo.User;
public interface UserMapper {
@Select("select * from t_user where username = #{name}")
User findUserByName(@Param("name") String name);
@Insert("insert into t_user(address,brithday,username, sex) values(#{user.address},#{user.brithday},#{user.name},#{user.sex})")
void addUser(@Param("user")User user);
}
User.java
public class User {
private Integer id;
private String name;
private Date brithday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date brithday) {
this.brithday = brithday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
}
UserService.java
import com.yunxiang.pojo.User;
public interface UserService {
User findUserByname(String name);
void addUser(User user);
}
UserServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.yunxiang.mapper.UserMapper;
import com.yunxiang.pojo.User;
import com.yunxiang.service.UserService;
import com.yunxiang.util.JsonUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private JedisPool jedisPool;
@Override
public User findUserByname(String name) {
User user=null;
String key = "user:"+name;
Jedis jedis = jedisPool.getResource();
String dataJson = jedis.get(key);
if(!StringUtils.isEmpty(dataJson)){
if(dataJson.equals("www")){
jedis.close();
return user;
}else{
jedis.close();
user= JsonUtils.jsonToPojo(dataJson, User.class);
return user;
}
}
System.out.println("从数据库中查询");
user = userMapper.findUserByName(name);
String userJson = JsonUtils.objectToJson(user);
if(user == null){
jedis.set(key, "www");
jedis.expire(key, 60);
jedis.close();
}else{
jedis.set(key, userJson);
jedis.close();
}
return user;
}
@Override
public void addUser(User user) {
userMapper.addUser(user);
}
}
JsonUtils.java
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将json结果集转化为对象
*
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将json数据转换成pojo对象list
*/
public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
#redis单服务器配置
spring.redis.database=0
spring.redis.host=192.168.163.128
spring.redis.port=6379
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=1000
注:springboot整合redis时,只需要在启动类中所有"@EnableCaching"开启支持缓存即可,然后在service层中,需要进行缓存的方法上,使用"@Cacheable(value=“user”)“注解进行缓存,其中value属性就是redis的key值的前缀,在查询时,springboot会根据查询结果的不同,会在value属的性值后面使用”:"来组合成新的key值。当缓存pojo对象时,该pojo对象必须要实现序列化。
springboot整合redis集群版
pom
<!-- 使用springmvc和spring的jar -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot整合mybatis,注解版 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- springboot整合redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
#redis集群版配置
spring.redis.cluster.nodes=192.168.163.130:7001,192.168.163.130:7002,192.168.163.130:7003,192.168.163.130:7004,192.168.163.130:7005,192.168.163.130:7006
RedisClusterConfiguration.java
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
@Configuration
public class RedisClusterConfiguration {
@Value("${spring.redis.cluster.nodes}")
private String redisNodes;
@Bean
public JedisCluster getJedisCluster(){
Set<HostAndPort> nodes = new HashSet<>();
String[] strs = redisNodes.split(",");
for(String str:strs){
String[] node = str.split(":");
HostAndPort hostAndPort = new HostAndPort(node[0],Integer.parseInt(node[1]));
nodes.add(hostAndPort);
}
JedisCluster cluster = new JedisCluster(nodes);
return cluster;
}
}
注:"RedisClusterConfiguration"是"JedisCluster"的配置类,所有"JedisCluster"可以操作redis集群
UserServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.yunxiang.mapper.UserMapper;
import com.yunxiang.pojo.User;
import com.yunxiang.service.UserService;
import com.yunxiang.util.JsonUtils;
import redis.clients.jedis.JedisCluster;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private JedisCluster jedisCluster;
@Override
public User findUserByname(String name) {
User user=null;
String key = "user:"+name;
try {
String json = jedisCluster.get(key);
if(!StringUtils.isEmpty(json)){
if(json.equals("www")){
return user;
}else{
user= JsonUtils.jsonToPojo(json, User.class);
return user;
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("从数据库中查询");
user = userMapper.findUserByName(name);
String json = JsonUtils.objectToJson(user);
try {
if(user == null){
jedisCluster.set(key, "www");
jedisCluster.expire(key, 60);
}else{
jedisCluster.set(key, json);
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
@Override
public void addUser(User user) {
userMapper.addUser(user);
}
}