SpringBoot整合Redis
实现步骤
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
配置yml文件
server:
port: 8088
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 1234
url: jdbc:mysql://localhost:3306/db1
redis:
host: 127.0.0.1
database: 0
port: 6379
Redis配置类
package com.test.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
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 org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* 配置redistemplate序列化
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* 选择redis作为默认缓存工具
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
//设置缓存有效一小时
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.
defaultCacheConfig().entryTtl(Duration.ofHours(1));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();
}
/**
* 配置redistemplate相关配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用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();
return template;
}
/**
* 对hash类型的数据操作
*/
public HashOperations<String,String,Object> hashOperations(RedisTemplate<String,Object> redisTemplate){
return redisTemplate.opsForHash();
}
/**
* 对redis字符串类型数据库操作
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 对链表类型的数据操作
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 对无序集合Set操作
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 对有序集合
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
创建实体类UserDomain
package com.test.domain;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("user")
public class UserDomain implements Serializable {
@TableId
private Integer id;
private String name;
private Integer age;
private String phone;
}
mapper
package com.test.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.domain.UserDomain;
@Repository
public interface UserMapper extends BaseMapper<UserDomain> {
}
service
package com.test.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.test.domain.UserDomain;
import java.util.List;
public interface UserService extends IService<UserDomain> {
/**
*查询所有用户
*/
List<UserDomain> findAll();
/**
*根据ID查询用户
*/
UserDomain findById(Integer id);
/**
*根据ID删除用户
*/
void deleteById(Integer id);
/**
* 更改用户
*/
void updateUser(UserDomain user);
}
service实现类
package com.test.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.Service;
import com.test.domain.UserDomain;
import com.test.mapper.UserMapper;
import com.test.service.UserService;
import javax.annotation.Resource;
import java.util.List;
/**
* @author cookie
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDomain> implements UserService {
@Resource
private UserMapper userMapper;
@Resource
RedisTemplate redisTemplate;
@Override
public List<UserDomain> findAll() {
String key = "user";
ListOperations<String,UserDomain> list = redisTemplate.opsForList();
if (redisTemplate.hasKey(key)) {
return list.range(key, 0, -1);
} else {
List<UserDomain> domainList = userMapper.selectList(null);
list.leftPushAll(key, domainList);
return domainList;
}
}
@Override
public UserDomain findById(Integer id) {
String key = "user"+id;
ValueOperations<String,UserDomain> operations = redisTemplate.opsForValue();
//判断缓存中是否有
if (redisTemplate.hasKey(key)) {
return operations.get(key);
}
UserDomain user = userMapper.selectById(id);
//添加到缓存中
operations.set(key, user);
return user;
}
@Override
public void deleteById(Integer id) {
String key = "user"+id;
userMapper.deleteById(id);
if (redisTemplate.hasKey(key)) {
//删除缓存
redisTemplate.delete(key);
}
}
@Override
public void updateUser(UserDomain user) {
String key = "user"+user.getId();
ValueOperations operations = redisTemplate.opsForValue();
userMapper.updateById(user);
if (redisTemplate.hasKey(key)) {
UserDomain userDomain = userMapper.selectById(user.getId());
operations.set(key,userDomain);
}
}
}
controller
package com.test.controller;
import com.test.domain.UserDomain;
import org.springframework.web.bind.annotation.*;
import com.test.service.UserService;
import javax.annotation.Resource;
import java.util.List;
/**
* @author cookie
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/find", method = RequestMethod.GET)
public List<UserDomain> find() {
return userService.findAll();
}
@RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
public UserDomain findUserById(@PathVariable("id") Integer id) {
return userService.findById(id);
}
@RequestMapping(value = "/deleteById/{id}", method = RequestMethod.GET)
public void deleteById(@PathVariable("id") Integer id) {
userService.deleteById(id);
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public void deleteById(@RequestBody UserDomain user) {
userService.updateUser(user);
}
启动项目,用postman测试查找所有用户
根据ID查询用户
完成。由于数据库脚本很简单,这里就不再展示了