直接代码,这里没有使用bean类
项目结构:
1.引入maven依赖
<properties> <java.version>1.8</java.version> <mybatis.version>2.1.0</mybatis.version> <artifactId>springboot-redis</artifactId> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.39</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <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>${mybatis.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> </dependencies>
2.配置文件 application.properties(也可配置到文件 application.yml)
#数据库的连接
spring.datasource.url=jdbc:mysql://localhost:3306/work?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000ms
logging.level.com.lh.springboot.mapper=debug
3.配置文件application.yml (也可配置到文件 application.properties)
mybatis: config-location: classpath:/mybatis/mybatis-config.xml # mybatis-config.xml 的文件地址 mapper-locations: classpath:/mybatis/mapper/*.xml # 所有以.xml 结尾的文件
4.配置主程序的运行类 (Springbootweb02Application)
1). @MapperScan(value = "com.lh.springboot.mapper")
该注解的意思是:指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
2). @EnableCaching
该注解的意思是:开启缓存管理功能
3). @SpringBootApplication
该注解的意思是:这个类是主程序类
5.配置config包下的类
//配置文件 RedisConfig
package com.lh.springboot.config;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration //用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> empRedisTemplate(RedisConnectionFactory redisConnectionFactory)throws Exception {
RedisTemplate<Object,Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// Json序列化配置
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(serializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory){
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600)) //存入Redis的时间设置600秒
//.entryTtl(Duration.ofDays(1))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();}
}
//配置文件 Myconfig
package com.lh.springboot.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * @program: springbootweb01 * @description: 配置类 * @author: li hui * @create: 2020-12-18 19:52 */ //@EnableWebMvc 全面接管mvc @Configuration public class MyConfig extends WebMvcConfigurationSupport {
//该类可不写 }
6.创建 mapper(包)下的UsersDao接口
//UserDao的接口
package com.lh.springboot.mapper; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; @Mapper //该注解是在编译之后会生成相应的接口实现类 (在主程序类注解了 @MapperScan() 在此处就可以省略) public interface UsersDao{ Object test(Map map); Integer updTest(Map map); Integer delTest(Map map); List<?> queryTest(); }
7.配置 mybatis包下的文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration>
<!--mybatis-config.xml 文件--> <!--<settings> <!– 打印查询语句 –> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings>--> <!--mybatis的插件配置--> </configuration>
<?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.lh.springboot.mapper.UsersDao"> <!--UserDao接口的全路径--> <!--UsersMapper.xml文件--> <select id="test" parameterType="map" resultType="map"> select * from users where id=#{id}; </select> <update id="updTest" parameterType="map"> update users set username=#{username},password=#{password},phone=#{phone},IDnumber=#{IDnumber} where id=#{id} </update> <delete id="delTest" parameterType="map"> delete from users where id=#{id} </delete> <select id="queryTest" resultType="map"> select username,password,phone,IDnumber,id from users </select> </mapper>
8.创建service包下的接口和 impl包下的实现类
//UserService 的接口
package com.lh.springboot.service; import java.util.List; import java.util.Map; public interface UsersService{ Object test(Map map); Map updTest(Map map); Integer delTest(Map map); List<?> queryTest(); }
//UsersServiceImpl (实现UsersService接口) 缓存注解也在本类来执行
package com.lh.springboot.service.impl; import com.lh.springboot.mapper.UsersDao; import com.lh.springboot.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service("usersService") public class UsersServiceImpl implements UsersService { private final UsersDao usersDao; @Autowired public UsersServiceImpl(UsersDao usersDao) { this.usersDao = usersDao; } @Override @Cacheable(cacheNames = {"test"}, key = "'user_'+#map.get('id')",unless="#result==null") public Object test(Map map) { System.out.println("测试query"); return usersDao.test(map); } @Override @CachePut(cacheNames = {"test"}, key = "'user_'+#map.get('id')",unless="#result==null") public Map updTest(Map map) { System.out.println("测试upd"); Integer integer = usersDao.updTest(map); if(integer==1){ return map; }else { return null; } } @Override @CacheEvict(cacheNames = "test", key = "'user_'+#map.get('id')",allEntries=false,beforeInvocation=false) public Integer delTest(Map map) { System.out.println("测试del"); return usersDao.delTest(map); } @Override @Cacheable(cacheNames = {"queryTest"},unless="#result==null") public List<?> queryTest() {
System.out.println("测试query全查") List<?> objects = usersDao.queryTest(); if(objects.size()<=0){ return null; }else { return objects; } }
/* @Cacheable 将方法的运行结果进行缓存 @Cacheable 以后再要相同的数据 直接从缓存中获取 就不用在执行方法了 几个属性 value/cacheNames 指定缓存的名字 key 缓存数据使用的key,默认使用方法参数的值 keyGenerator:key的生成器,可以自己指定key的生成器的组件id key/keyGenerator: 二选一 cacheManager:指定缓存管理器 或者cacheResolver指定缓存解析器 二选一 condition:指定符合条件的情况下才缓存 unless:否定缓存,当unless指定的条件是true,我们的方法返回值就不会被缓存 可以获取到结果进行判断 sync:是否使用异步模式 */ /* @CachePut 缓存更新 @CacheEvict 清楚缓存 */
}
9.创建controller包下的类
package com.lh.springboot.controller; import com.alibaba.fastjson.JSON; import com.lh.springboot.service.UsersService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @Controller @Scope("prototype") public class UsersController{ private final UsersService usersService; @Autowired public UsersController(UsersService usersService) { this.usersService = usersService; } @GetMapping(value = "/aa") @ResponseBody public Object aa(@RequestParam Map map){ return usersService.test(map); } @GetMapping(value = "/bb") @ResponseBody public Map bb(@RequestParam Map map){ return usersService.updTest(map); } @GetMapping(value = "/cc") @ResponseBody public Integer cc(@RequestParam Map map){ return usersService.delTest(map); } @GetMapping(value = "/dd") @ResponseBody public String dd(){ List<?> objects = usersService.queryTest(); return JSON.toJSONString(objects); } }
10.启动主程序类
11,打开网页进行测试
1.mysql数据库的值为
2.启动Redis数据库 (此时无数据)
3.访问 http://127.0.0.1:8080/aa?id=1 返回id为1的数据
1)查看Redis的数据 此时数据存到了Redis里有效时间600秒
2)查看控制台上的输出
可以看出,程序访问了mysql数据表
3)刷新页面 再次查看控制台输出
4)修改数据(修改缓存) 查看控制台输出 http://127.0.0.1:8080/bb?username=00&password=00&phone=00&IDnumber=00&id=1
可以看出 我修改一条数据控制台也有打印,Redis的值也随着发生变化
5)再次查询id为1的数据 http://127.0.0.1:8080/aa?id=1
再次查看控制台
当我们修改结束,再次查看数据,没有输出 就是直接查的是Redis的缓存数据没有查询mysql的表数据
6)清除缓存 http://127.0.0.1:8080/cc?id=1 (删除id为1的数据)
删除成功
Redis数据也确实删除了
我们再次查询删除的id为1的数据
缓存也清除成功!