SpringBoot整合Mysql和Redis的詳細過程

一、項目創建 

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層接口測試

到此這篇關於SpringBoot整合Mysql、Redis的文章就介紹到這瞭,更多相關SpringBoot整合Mysql、Redis內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: