SpirngBoot整合redis做缓存Demo

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: SpirngBoot整合redis做缓存Demo

环境准备


下载


项目代码


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,这里面有语法,自己注意一下


7.png


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的值修改为新的数据


8.png


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中


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
1天前
|
存储 缓存 NoSQL
Redis入门到通关之Redis缓存数据实战
Redis入门到通关之Redis缓存数据实战
|
3天前
|
存储 缓存 运维
软件体系结构 - 缓存技术(5)Redis Cluster
【4月更文挑战第20天】软件体系结构 - 缓存技术(5)Redis Cluster
136 10
|
10天前
|
缓存 NoSQL Java
使用Redis进行Java缓存策略设计
【4月更文挑战第16天】在高并发Java应用中,Redis作为缓存中间件提升性能。本文探讨如何使用Redis设计缓存策略。Redis是开源内存数据结构存储系统,支持多种数据结构。Java中常用Redis客户端有Jedis和Lettuce。缓存设计遵循一致性、失效、雪崩、穿透和预热原则。常见缓存模式包括Cache-Aside、Read-Through、Write-Through和Write-Behind。示例展示了使用Jedis实现Cache-Aside模式。优化策略包括分布式锁、缓存预热、随机过期时间、限流和降级,以应对缓存挑战。
|
18天前
|
存储 缓存 NoSQL
使用redis进行缓存加速
使用redis进行缓存加速
27 0
|
19天前
|
存储 缓存 NoSQL
Java手撸一个缓存类似Redis
`LocalExpiringCache`是Java实现的一个本地缓存类,使用ConcurrentHashMap存储键值对,并通过ScheduledExecutorService定时清理过期的缓存项。类中包含`put`、`get`、`remove`等方法操作缓存,并有`clearCache`方法来清除过期的缓存条目。初始化时,会注册一个定时任务,每500毫秒检查并清理一次过期缓存。单例模式确保了类的唯一实例。
16 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
1月前
|
存储 缓存 NoSQL
[Redis]——缓存击穿和缓存穿透及解决方案(图解+代码+解释)
[Redis]——缓存击穿和缓存穿透及解决方案(图解+代码+解释)
255 0
|
16天前
|
NoSQL Linux Redis
06- 你们使用Redis是单点还是集群 ? 哪种集群 ?
**Redis配置:** 使用哨兵集群,结构为1主2从,加上3个哨兵节点,总计分布在3台Linux服务器上,提供高可用性。
228 0
|
24天前
|
负载均衡 监控 NoSQL
Redis的集群方案有哪些?
Redis集群包括主从复制(基础,手动故障恢复)、哨兵模式(自动高可用)和Redis Cluster(官方分布式解决方案,自动分片和容错)。此外,还有如Codis、Redisson和Twemproxy等第三方工具用于代理和负载均衡。选择方案需考虑应用场景、数据规模和并发需求。
191 2
|
30天前
|
NoSQL Redis
Redis集群(六):集群常用命令及说明
Redis集群(六):集群常用命令及说明
187 0

热门文章

最新文章