一、项目创建
1.1 创建项目
在IDEA中,File--New--Project--Spring Initializer
名称为springboot-mysql-redis
1.2 目录结构
1.3 pom.xml配置文件
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC username: root password: 1234 redis: host: localhost port: 6379 server: port: 8080 mybatis: mapper-locations: classpath:mapper/*xml type-aliases-package: com.xsbc.entity # 开启驼峰命名 configuration: map-underscore-to-camel-case: true
二、初始化数据库
drop database if exists blog; create database blog; user blog; drop table if exists user; create table user( id int(11) not null, name varchar(255) DEFAULT "", age int(11) DEFAULT 0, PRIMARY KEY(id) )ENGINE=INNODB DEFAULT CHARSET=utf8; insert into user values(1,'小王',20); insert into user values(2,'老李',23);
三、初始化代码
3.1 实体类entity
@Data @NoArgsConstructor @AllArgsConstructor public class User { private int id; private String name; private int age; }
3.2 Mapper接口类
@Mapper public interface UserMapper { ListgetAllUsers(); int updateUser(Integer id); }
xml映射文件
update user set age=age+2 where id=#{id}
3.3 Redis工具类
1)config包创建类
Redis常量类RedisConstant
public class RedisConstant { public static String ALL_USER_KEY="allUser"; }
Redis配置类RedisConfig
@Configuration public class RedisConfig { @Resource private RedisTemplate redisTemplate; @Bean public RedisTemplate redisTemplateInit(){ //序列化key的实例化对象 redisTemplate.setKeySerializer(new StringRedisSerializer()); //序列化value的实例化对象 redisTemplate.setValueSerializer( new GenericJackson2JsonRedisSerializer()); return redisTemplate; } }
2)util包下创建类
@Component public class RedisUtil { @Resource private RedisTemplateredisTemplate; public void setRedisTemplate(RedisTemplate redisTemplate){ this.redisTemplate=redisTemplate; } // 指定缓存失效时间 public boolean expire(String key,long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } // 根据key获取过期时间 public long getExpire(String key){ return redisTemplate.getExpire(key,TimeUnit.SECONDS); // 判断key是否存在 public boolean hasKey(String key){ return redisTemplate.hasKey(key); }catch(Exception e){ // 删除缓存 @SuppressWarnings("unchecked") public void del(String... key){ if (key!=null&&key.length> 0){ if (key.length==1) { redisTemplate.delete(key[0]); }else{ redisTemplate.delete( (Collection )CollectionUtils.arrayToList(key)); // 普通缓存获取 public Object get(String key){ return key==null?null:redisTemplate.opsForValue().get(key); // 普通缓存放入 public boolean set(String key,Object value){ redisTemplate.opsForValue().set(key,value); // 普通缓存放入并设置时间 public boolean set(String key,Object value,long time){ try{ if(time>0){ redisTemplate.opsForValue() .set(key,value,time,TimeUnit.SECONDS); set(key,value); // 递增 public long incr(String key,long delta){ if(delta<0){ throw new RuntimeException("递增因子必须大于0"); return redisTemplate.opsForValue().increment(key,delta); // 递减 public long decr(String key, long delta){ throw new RuntimeException("递减因子必须大于0"); return redisTemplate.opsForValue().increment(key,-delta); // HashGet public Object hget(String key,String item){ return redisTemplate.opsForHash().get(key,item); // 获取hashKey对应的所有键值 public Map
3.4 Service层
1)UserService接口类
public interface UserService { public ListgetAllUsers(); public void updateUserAge(); }
2)接口实现类
@Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Autowired private RedisUtil redisUtil; @Override public ListgetAllUsers() { List users=(List )redisUtil .get(RedisConstant.ALL_USER_KEY); if(CollectionUtils.isEmpty(users)){ users=userMapper.getAllUsers(); redisUtil.set(RedisConstant.ALL_USER_KEY,users); } return users; } @Transactional public void updateUserAge() { redisUtil.del(RedisConstant.ALL_USER_KEY); userMapper.updateUserAgeById(1); userMapper.updateUserAgeById(2); }
3.5 Controller层
@Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/getAll") @ResponseBody public ListgetUsers(){ return userService.getAllUsers(); } @RequestMapping("/update") @ResponseBody public int updateUser(){ userService.updateUserAge(); return 1; } }
四、单元测试
4.1 Respository和Service层单元测试
@SpringBootTest class SpringbootMysqlRedisApplicationTests { @Autowired private UserMapper userMapper; private UserService userService; @Test void testUserMapper(){ userMapper.updateUserAgeById(1); Listusers=userMapper.getAllUsers(); for(User user:users){ System.out.println(user); } } void testUserService(){ userService.updateUserAge(); List users=userService.getAllUsers(); }
4.2 Controller层接口测试
到此这篇关于SpringBoot整合Mysql、Redis的文章就介绍到这了,更多相关SpringBoot整合Mysql、Redis内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!