笔记标题 | 青训营笔记

66 阅读1分钟

这是我参与「第四届青训营 」笔记创作活动的第4天

SpringBoot和Redis小Demo

1.创建Maven工程

掠过~

2.添加相关依赖

  • Redis
  • 通用池
  • Mysql
  • MyBatis
  • 通用mapper
  • lombok
  • web
  • test
<dependencies>
    <!-- Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- 通用池 -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <!-- Mysql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <!-- 通用mapper -->
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.1.5</version>
    </dependency>
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <!-- 测试 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>

3.配置

  • 端口
  • mysql数据源
  • redis数据源
  • log
  • mybatis
# 端口,mysql数据源,redis数据源,mybatis,log日志
server:
  port: 9998
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db_test

  redis:
    host: localhost
    port: 6379
    timeout: 1000
    jedis:
      pool:
        min-idle: 5
        max-idle: 10
        # 永不过期
        max-wait: -1

mybatis:
  mapper-locations: classpath:/mybatis/mapper/*.xml
  type-aliases-package: com.redis.entities
  configuration:
    map-underscore-to-camel-case: true

4.业务实现

  • 简单使用Redis
package com.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author LBS59
 * @description Redis控制器
 */
@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/redis/get/{key}")
    public Object get(@PathVariable("key") String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @PostMapping(value = "/redis/set/{key}/{value}")
    public Object set(@PathVariable("key") String key, @PathVariable("value") String value) {
        redisTemplate.opsForValue().set(key, value);
        return "set success";
    }
}
# 端口,mysql数据源,redis数据源,mybatis,log日志
server:
  port: 9998
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db_test

  redis:
    host: localhost
    port: 6379
    timeout: 1000
    jedis:
      pool:
        min-idle: 5
        max-idle: 10
        # 永不过期
        max-wait: -1

mybatis:
  mapper-locations: classpath:/mybatis/mapper/*.xml
  type-aliases-package: com.redis.entities
  configuration:
    map-underscore-to-camel-case: true
package com.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author LBS59
 * @description redis配置类
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        // 指定k-v的序列化方式
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        // redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        return redisTemplate;
    }
}
  • 并发缓存测试
package com.redis.service.impl;

import com.redis.entities.Emp;
import com.redis.mapper.EmpMapper;
import com.redis.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author LBS59
 * @description 业务逻辑层接口实现
 */
@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private EmpMapper empMapper;


    @Override
    public void add(Emp emp) {
        empMapper.insert(emp);
    }

    @Override
    public Object getEmpById(Integer id) {
        // 先从缓存中获取数据,如果缓存中有,则直接返回,如果无,则查询mysql,并将数据设置到缓存中
        String key = "user:" + id;
        Object userObj = redisTemplate.opsForValue().get(key);
        if (userObj == null) {
            synchronized (this.getClass()) {
                userObj = redisTemplate.opsForValue().get(key);
                if (userObj == null) {
                    log.debug("-----> 查询数据库 --------");
                    // 查数据库
                    Emp emp = empMapper.selectByPrimaryKey(id);
                    redisTemplate.opsForValue().set(key, emp);
                    return emp;
                } else {
                    log.debug("-------> 查询Redis缓存(同步代码块)>>>>>>>>>");
                }
            }
        } else {
            log.debug("--------> 查询Redis缓存 >>>>>>>>");
        }
        return userObj;
    }
}