根据:wuzhengjun博客的步骤实现的整合Demo
1.导入pom.xml配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2.添加application.yml配置文件,添加Redis配置
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.hjl.pojo
#打印sql语句
logging:
level:
com.hjl.dao: debug # 改成你的mapper文件所在包路径
#将themilef的默认缓存禁用,热加载生效
thymeleaf:
cache: false
#redis配置
redis:
database: 0 # Redis数据库索引(默认为0)
host: localhost #Redis服务器地址
port: 6379 # Redis服务器连接端口
password: #Redis服务器连接密码(默认为空)
timeout: 12000 #redis 超时时间
# password:
pool:
minIdle: 1 #redis最小空闲连接
maxIdle: 10 #redis最大空闲连接
maxWait: 3 #redis最大阻塞等待时间(负值表示无限制)
maxActive: 8 #redis最大池连接数
3.创建UserInfo实体类,并添加序列化id
注意:要缓存的 Java 对象必须实现 Serializable 接口,因为 Spring 会将对象先序列化再存入 Redis。
package com.hjl.pojo;
import java.io.Serializable;
public class User implements Serializable {
//定义程序序列化ID
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
4.创建UserMapper接口,方法名对应UserMapper.xml中的id
package com.hjl.dao;
import com.hjl.pojo.UserInfo;
import java.util.List;
public interface UserMapper {
List<UserInfo> select();
UserInfo findById(String id);
int delete(String id);
int update(String id);
}
5.创建UserMapper.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.hjl.dao.UserMapper">
<!--我自己加的方法-->
<select id="select" resultType="com.hjl.pojo.User">
select * from userinfo
</select>
<select id="findById" resultType="com.hjl.pojo.User" parameterType="String">
select * from user where id = #{id}
</select>
<update id="update" parameterType="String">
update user set name = 'tom'
where id = #{id}
</update>
<delete id="delete" parameterType="String">
delete from user where id = #{id}
</delete>
</mapper>
6.创建UserService接口
package com.hjl.service;
import com.hjl.pojo.UserInfo;
import java.util.List;
public interface UserService {
List<UserInfo> select();
UserInfo findById(String id);
int delete(String id);
int update (String id);
}
5.创建UserServiceImpl类实现UserServcie接口
package com.hjl.service.impl;
import com.hjl.dao.UserMapper;
import com.hjl.pojo.User;
import com.hjl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service(value="UserService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public List<User> select() {
return userMapper.select();
}
@Override
public User findById(String id) {
String key = "user_"+id;
//先从缓存获取用户,如果没有再从数据库获取
ValueOperations<String, User> valueOperations = redisTemplate.opsForValue();
boolean haskey = redisTemplate.hasKey(key);
if(haskey){
User user = valueOperations.get(key);
System.out.println("缓存中获取数据=="+user.getName());
return user;
}else {
User user = userMapper.findById(id);
System.out.println("从数据库=="+user.getName());
valueOperations.set(key,user,5, TimeUnit.HOURS); //写入缓存
return user;
}
}
@Override
public int delete(String id) {
int result = userMapper.delete(id);
String key = "user_"+id;
//先删除数据库数据再删除缓存数据
if(result != 0){
if(redisTemplate.hasKey(key)){
redisTemplate.delete(key);
}
}
return result;
}
@Override
public int update(String id) {
int result = userMapper.update(id);
String key = "user_" + id;
if(result!=0){
if(redisTemplate.hasKey(key)){
redisTemplate.delete(key);
}
//重新写入缓存
User user = userMapper.findById(id);
redisTemplate.opsForValue().set(key,user,5,TimeUnit.HOURS);
}
return result;
}
}
6.创建控制层UserController
package com.hjl.controller;
import com.hjl.dao.UserMapper;
import com.hjl.pojo.User;
import com.hjl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = {"/user"})
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping(value = {"/select"}, produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
public List<User> getAllUsers() {
List<User> list = userService.select();
return list;
}
@GetMapping("/findById/{id}")
public User test(@PathVariable("id") String id) {
return userService.findById(id);
}
@GetMapping("/del/{id}")
public int delele(@PathVariable("id") String id) {
return userService.delete(id);
}
@GetMapping("/up/{id}")
public int up(@PathVariable("id") String id) {
return userService.update(id);
}
}
7.启动项目
ps:需要先启动redis
访问:http://localhost:8080/user/findById/4
再次访问
github地址:https://github.com/123ac/Redis-Demo