环境准备
下载
项目代码
Demoo: SSM,SpringBoot or other demo - Gitee.com
redis可视化工具RedisDesktopManager下载
链接:https://pan.baidu.com/s/1e3hVvR5du4Ullv9InjqdSw
提取码:yq07
复制这段内容后打开百度网盘手机App,操作更方便哦
SpringBoot 整合MyBatis
redis环境准备
环境搭建
测试连接
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
package com.imooc.demo; import redis.clients.jedis.Jedis; public class MyRedis { public static void main(String args[]) { // 连接redis服务 Jedis jedis = new Jedis("47.105.132.96", 6379); //jedis.auth("123456"); //如果redis有设置密码 // 查看服务是否运行 System.out.println("Server is running: " + jedis.ping()); String name=jedis.get("name"); System.out.println(name); } }
整合redis
注意
项目在上面SpringBoot整合MyBatis的基础上修改的
pom.xml
<dependencies> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</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>1.3.4</version> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
application.properties
添加redis的访问ip地址,我的redis没有密码
###################################### ###redis ###################################### spring.redis.host=47.105.132.96
redis配置类
作用:使数据存入redis以json方法存储
package com.example.demo.config; import java.net.UnknownHostException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.Jackson2JsonRedisSerializer; import com.example.demo.entity.User; @Configuration public class RedisConfig { /** * 为 User类添加RedisSerializer 序列号器规则,使其存的方式为JSON */ @Bean public RedisTemplate<Object, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<Object, User> template = new RedisTemplate<Object, User>(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<User> serializer = new Jackson2JsonRedisSerializer<>(User.class); template.setDefaultSerializer(serializer); return template; } @Bean public RedisCacheManager userCacheManager(RedisTemplate<Object, User> userRedisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(userRedisTemplate); cacheManager.setUsePrefix(true); return cacheManager; } }
service层(敲黑板)(敲黑板)(敲黑板)
@CacheConfig
@Cacheable(value = "user", key = "#id")
@CachePut(value = "user", key = "#user.id")
@CacheEvict(value = "user", key = "#id")
1)@CacheConfig里的cacheNames属性和其余3个注解中的value属性一样,都是代表下图中的上面箭头
2)@Cacheable @CachePut @CacheEvict 里的key属性设置存缓存中的数据的 key,如下图中的第二个箭头,
如果没有指定key,默认为key为方法的参数,value为方法返回的值,我们要设置key为user的id,这里面有语法,自己注意一下
package com.example.demo.service; import java.util.Date; 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.example.demo.dao.UserMapper; import com.example.demo.entity.User; /** * (1)如果在类上加上下面注解 * @CacheConfig(cacheNames="user") * 则所有方法中@Cacheable,@CachePut,@CacheEvict 的(value = "user")可以省略 * (2)(cacheManager="userCacheManager") 有多个cacheManager告诉当前service用哪个cacheManager */ @CacheConfig(cacheManager="userCacheManager") @Service public class UserService { @Autowired private UserMapper userMapper; @Cacheable(value = "user", key = "#id") public User getUser(Integer id) { System.out.println("查询:" + id); User user = userMapper.selectByPrimaryKey(id); return user; } /* * @CachePut (1)先调用方法 (2)再缓存数据 * 注意:@CachePut(value="user") */ @CachePut(value = "user", key = "#user.id") public User updateUser(User user) { user.setName(new Date().toString()); System.out.println("修改:" + user.getId()); // dao.update(user); return user; } /* * @CacheEvict : 清除缓存 */ @CacheEvict(value = "user", key = "#id") public void deleteUser(Integer id) { System.out.println("delete :"+id); //dao.delete(id); } }
控制层
package com.example.demo.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.dao.UserMapper; import com.example.demo.entity.User; import com.example.demo.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{id}") public User selectUser(@PathVariable("id") int id) { User user = userService.getUser(id); return user; } @GetMapping("/updateuser/{id}") public String updateUser(@PathVariable("id") int id) { //根据id修改user,没查数据库 User user=new User(); user.setId(id); user.setName("1"); user.setPassword("1"); user.setSign(1); userService.updateUser(user); return "success"; } @GetMapping("/deleteuser/{id}") public String deleteUser(@PathVariable("id") int id) { userService.deleteUser(id); return "success"; } }
启动类
添加 @EnableCaching,开启缓存功能
@SpringBootApplication @EnableCaching public class SpringBootCacheApplication { public static void main(String[] args) { SpringApplication.run(SpringBootCacheApplication.class, args); } }
测试(按照下面顺序访问下面url)
1) http://localhost:8080/user/1
查询user,发送SQL,把key为1的数据放在redis中
2)http://localhost:8080/user/1
查询user,不发送SQL,甚至不走service.selectUser()方法
3)http://localhost:8080/user/2
查询user,发送SQL,把key为2的数据放在redis中
4)http://localhost:8080/updateuser/1
修改id为1的user(上面的修改代码没有连接数据库,直接写死,重点测试缓存),redis中的key为user:1的值修改为新的数据
5) http://localhost:8080/user/1
查询user,不发送SQL,查询到修改后的新数据
6)http://localhost:8080/deleteuser/1
删除缓存中,即redis中key为user:1的数据
7) http://localhost:8080/user/1
查询user,发送SQL,把key为1的数据放在redis中