SpringBoot整合Mysql、Redis
路上的追梦人 人气:0一、项目创建
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 { List<User> getAllUsers(); int updateUser(Integer id); }
xml映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xsbc.mapper.UserMapper"> <select id="getAllUsers" resultType="com.xsbc.entity.User"> select * from user </select> <!-- User类的id参数是int类型,mysql默认是Integer --> <update id="updateUserAgeById" parameterType="java.lang.Integer"> update user set age=age+2 where id=#{id} </update> </mapper>
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 RedisTemplate<String,Object> redisTemplate; public void setRedisTemplate(RedisTemplate<String,Object> 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<String>)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<Object, Object> hmget(String key){ return redisTemplate.opsForHash().entries(key); // HashSet public boolean hmset(String key,Map<String, Object> map){ redisTemplate.opsForHash().putAll(key,map); // HashSet 并设置时间 public boolean hmset(String key,Map<String, Object> map,long time){ redisTemplate.opsForHash().putAll(key, map); if (time>0){ expire(key,time); // 向一张hash表中放入数据,如果不存在将创建 public boolean hset(String key,String item,Object value){ redisTemplate.opsForHash().put(key,item,value); public boolean hset(String key,String item,Object value,long time){ // 删除hash表中的值 public void hdel(String key,Object... item) { redisTemplate.opsForHash().delete(key,item); // 判断hash表中是否有该项的值 public boolean hHasKey(String key,String item) { return redisTemplate.opsForHash().hasKey(key,item); // hash递增 如果不存在,就会创建一个 并把新增后的值返回 public double hincr(String key,String item,double by) { return redisTemplate.opsForHash().increment(key,item,by); // hash递减 public double hdecr(String key,String item,double by) { return redisTemplate.opsForHash().increment(key,item,-by); // 根据key获取Set中的所有值 public Set<Object> sGet(String key) { return redisTemplate.opsForSet().members(key); return null; // 根据value从一个set中查询,是否存在 public boolean sHasKey(String key,Object value) { return redisTemplate.opsForSet().isMember(key,value); // 将数据放入set缓存 public long sSet(String key,Object... values) { return redisTemplate.opsForSet().add(key,values); return 0; // 将set数据放入缓存 public long sSetAndTime(String key,long time,Object... values){ Long count=redisTemplate.opsForSet().add(key,values); if (time> 0)expire(key, time); return count; // 获取set缓存的长度 public long sGetSetSize(String key){ return redisTemplate.opsForSet().size(key); // 移除值为value的 public long setRemove(String key,Object... values){ Long count=redisTemplate.opsForSet().remove(key,values); // 获取list缓存的内容 public List<Object> lGet(String key,long start,long end){ return redisTemplate.opsForList().range(key,start,end); // 获取list缓存的长度 public long lGetListSize(String key){ return redisTemplate.opsForList().size(key); // 通过索引 获取list中的值 public Object lGetIndex(String key,long index){ return redisTemplate.opsForList().index(key,index); // 将list放入缓存 public boolean lSet(String key, Object value){ redisTemplate.opsForList().rightPush(key,value); public boolean lSet(String key,Object value,long time){ if (time > 0) expire(key, time); public boolean lSet(String key, List<Object> value){ redisTemplate.opsForList().rightPushAll(key,value); public boolean lSet(String key,List<Object> value,long time){ if(time>0) expire(key, time); // 根据索引修改list中的某条数据 public boolean lUpdateIndex(String key,long index,Object value){ redisTemplate.opsForList().set(key,index,value); // 移除N个值为value public long lRemove(String key,long count,Object value){ Long remove=redisTemplate.opsForList().remove(key,count,value); return remove; }
3.4 Service层
1)UserService接口类
public interface UserService { public List<User> getAllUsers(); public void updateUserAge(); }
2)接口实现类
@Service("userService") public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Autowired private RedisUtil redisUtil; @Override public List<User> getAllUsers() { List<User> users=(List<User>)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 List<User> getUsers(){ 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); List<User> users=userMapper.getAllUsers(); for(User user:users){ System.out.println(user); } } void testUserService(){ userService.updateUserAge(); List<User> users=userService.getAllUsers(); }
4.2 Controller层接口测试
加载全部内容