SpringBoot整合Mysql和Redis的详细过程

网友投稿 407 2022-08-26


SpringBoot整合Mysql和Redis的详细过程

目录一、项目创建 1.1创建项目1.2目录结构1.3pom.xml配置文件二、初始化数据库三、初始化代码3.1实体类entity3.2Mapper接口类3.3Redis工具类3.4Service层3.5Controller层四、单元测试http://4.1Respository和Service层单元测试4.2Controller层接口测试

一、项目创建

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

@NoArgsCZtDmIvcaonstructor

@AllArgsConstructor

public class User {

private int id;

private String name;

private int age;

}

3.2 Mapper接口类

@Mapper

public interface UserMapper {

List getAllUsers();

int updateUser(Integer id);

}

xml映射文件

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from user

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 RedisTemplate redisTemplate;

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 hmget(String key){

return redisTemplate.opsForHash().entries(key);

// HashSet

public boolean hmset(String key,Map map){

redisTemplate.opsForHash().putAll(key,map);

// HashSet 并设置时间

public boolean hmset(String key,Map 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 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 lGet(String key,long start,long end){

return redisTemplate.opsForList().range(key,start,end);

// 获取list缓存的长度

public long lGethttp://ListSize(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 value){

redisTemplate.opsForList().rightPushAll(key,value);

public boolean lSet(String key,List 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 getAllUsers();

public void updateUserAge();

}

2)接口实现类

@Service("userService")

public class UserServiceImpl implements UserService {

@Resource

private UserMapper userMapper;

@Autowired

private RedisUtil redisUtil;

@Override

public List getAllUsers() {

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 List getUsers(){

return userService.getAllUsers();

}

@RequestMapping("/update")

@ResponseBody

public int updateUser(){

userService.updateUserAge();

return 1;

}

}

四、单元测试http://

4.1 Respository和Service层单元测试

@SpringBootTest

class SpringbootMysqlRedisApplicationTests {

@Autowired

private UserMapper userMapper;

private UserService userService;

@Test

void testUserMapper(){

userMapper.updateUserAgeById(1);

List users=userMapper.getAllUsers();

for(User user:users){

System.out.println(user);

}

}

void testUserService(){

userService.updateUserAge();

List users=userService.getAllUsers();

}

4.2 Controller层接口测试


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python-3.数字运算,变量,格式化输出(python把数值换成字符)
下一篇:python-5.原样输出,转义字符(python中转义字符用法及例子)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~