用Redis和MyBatis完成缓存数据的增加、删除、修改、查询

1. 安装Redis

Redis在Windows上不支持,在Windows上可以先安装WSL(即Linux)。

CMD用管理员打开,执行wsl --install。安装完成后重启电脑。如果Linux没启动。点击开始按钮,在最近添加里面有Ubuntu,以管理员身份打开。

安装Redis

sudo apt-add-repository ppa:redislabs/redis
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install redis-server

启动Redis

sudo service redis-server start

Install Redis on Windows | Redis

Redis 安装_redis教程

2. 在Spring Boot中集成Redis

添加Redis, MySQL, MyBatis依赖

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.2</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-data-redis</artifactId>
		</dependency>

在application.properties中配置MySQL、Redis服务器

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_test
spring.datasource.username=user
spring.datasource.password=123
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.sql.init.mode=always

spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=5000

在入口类加上@EnableCaching注解,开启缓存支持。

3. 配置Redis类

@Configuration
public class RedisConfig extends CachingConfigurerSupport{

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory factory) {
		RedisCacheManager cacheManager = RedisCacheManager.create(factory);
		return cacheManager;
	}
	
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(factory);
		return redisTemplate;
	}
	
	@Bean
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(factory);
		return stringRedisTemplate;
	}
	
}

4. 创建实体类

@Data
public class User implements Serializable{

	private int id;
	private String name;
	private int age;
}

5. 实现实体和数据表的映射关系

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface UserMapper {

	@Select("SELECT * FROM user WHERE id = #{id}")
	User queryById(@Param("id") int id);
	
	@Select("SELECT * FROM user")
	List<User> queryAll();
	
	@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
	int add(User user);
	
	@Delete("DELETE FROM user WHERE id = #{id}")
	int delById(int id);
	
	@Update("UPDATE user SET name=#{name},age=#{age} WHERE ID = #{id}")
	int updateById(User user);
}

6. 创建Redis缓存服务层

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.User;
import com.UserMapper;

@Service
@CacheConfig(cacheNames = "users")
public class UserService {

	@Autowired
	UserMapper userMapper;
	
	//key="#p0":指定传入的第1个参数作为Redis的key
	@Cacheable(key="#p0")
	public User selectUser(int id) {
		simulateSlowService();
		System.out.println("select");
		return userMapper.queryById(id);
	}
	
	@CachePut(key="#p0.id")
	public void updateById(User user) {
		System.out.println("update");
		userMapper.updateById(user);
	}
	
	//allEntries = true方法调用后将立即清除缓存
	@CacheEvict(key = "#p0", allEntries = true)
	public void deleteById(int id) {
		System.out.println("delete");
		userMapper.delById(id);
	}
	
  // Don't do this at home
	private void simulateSlowService() {
		try {
			long time = 3000L;
			Thread.sleep(time);
		} catch (InterruptedException e) {
			throw new IllegalStateException(e);
		}
	}	
}

7. 添加测试

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class AppRunner implements CommandLineRunner{

	private static Logger logger = LoggerFactory.getLogger(AppRunner.class);
	
	private UserService userService;
	
	public AppRunner(UserService userService) {
		// TODO Auto-generated constructor stub
		this.userService = userService;
	}
	
	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		logger.info("...Fetching");
		logger.info("user-1" + userService.selectUser(1));
		logger.info("user-2" + userService.selectUser(2));
		logger.info("user-1" + userService.selectUser(1));
		logger.info("user-2" + userService.selectUser(2));
		logger.info("user-1" + userService.selectUser(1));
		logger.info("user-1" + userService.selectUser(1));
	}

}

8. resources/schema.sql

DROP TABLE IF EXISTS user;
CREATE TABLE user (
    id int(11) NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT NULL,
    age int(11) DEFAULT NULL,
    PRIMARY KEY (id)
);

INSERT INTO user VALUES (1, 'aa', 18);
INSERT INTO user VALUES (2, 'bb', 18);
INSERT INTO user VALUES (3, 'cc', 18);

9. 启动项目,查看执行结果:

 第一次时出现select信息,代表对数据库进行了查询操作,后面再访问时则不会出现提示,表示没有对数据库执行操作,而是使用Redis中的缓存数据。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值