配套视频:SpringBoot3整合Redis&基础操作视频
SpringBoot是一种用于构建Java应用程序的开发框架,Redis是一个高性能的键值存储数据库,常用于缓存、会话管理、消息队列等应用场景,本文将给大家介绍,基于最新的的SpringBoot3基础上如何集成Redis,并实现Redis基本应用操作。
环境准备
创建项目
Maven依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis com.mysql mysql-connector-j org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.baomidou mybatis-plus-boot-starter 3.5.5 org.mybatis mybatis-spring 3.0.3
yml依赖,注意先创建好一个数据库testdb
server: port: 9999 spring: data: redis: host: localhost port: 6379 datasource: username: root password: 123456 url: jdbc:mysql:///testdb
Redis配置类
@Configuration @EnableCaching public class RedisConfig { @Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer
使用RedisTemplate进行常见的Redis操作,如存储、检索和删除数据。
String
// 普通字符串 String key1 = "user:token:0001"; redisTemplate.opsForValue().set(key1, UUID.randomUUID().toString(), 30, TimeUnit.MINUTES); System.out.println(redisTemplate.opsForValue().get(key1)); // 计数 String key2 = "article:A00001:viewsCount"; redisTemplate.opsForValue().increment(key2); System.out.println(redisTemplate.opsForValue().get(key2)); // 对象 HashMapuser = new HashMap<>(); user.put("id", "0001"); user.put("name", "张三疯"); user.put("age", 28); user.put("birthday", new Date(2008 - 1900, 10, 03)); String key3 = "user:0001"; redisTemplate.opsForValue().set(key3, user); System.out.println(redisTemplate.opsForValue().get(key3));
hash
String key4 = "user:0001:cart"; MapshoppingCart = new HashMap<>(); shoppingCart.put("cartId", "123456789"); shoppingCart.put("userId", "987654321"); List
set
String key5 = "author:0001:fans"; redisTemplate.opsForSet().add(key5, "张三", "李四", "王五"); System.out.println("粉丝数:" + redisTemplate.opsForSet().size(key5));
zset
String key5 = "user:0001:friends"; redisTemplate.opsForZSet().add(key5,"张三", System.currentTimeMillis()); redisTemplate.opsForZSet().add(key5,"李四", System.currentTimeMillis()); redisTemplate.opsForZSet().add(key5,"王五", System.currentTimeMillis()); SetfriendList = redisTemplate.opsForZSet().reverseRange(key5, 0L, -1L); System.out.println("好友列表:" + friendList );
list
String key6 = "order:queue"; Maporder1 = new HashMap<>(); order1.put("orderId", "1001"); order1.put("userId", "2001"); order1.put("status", "已完成"); order1.put("amount", 500.75); order1.put("creationTime", "2024-03-07T09:30:00"); order1.put("lastUpdateTime", "2024-03-07T10:45:00"); order1.put("paymentMethod", "在线支付"); order1.put("shippingMethod", "自提"); order1.put("remarks", "尽快处理"); Map order2 = new HashMap<>(); order2.put("orderId", "1002"); order2.put("userId", "2002"); order2.put("status", "待处理"); order2.put("amount", 280.99); order2.put("creationTime", "2024-03-07T11:00:00"); order2.put("lastUpdateTime", "2024-03-07T11:00:00"); order2.put("paymentMethod", "货到付款"); order2.put("shippingMethod", "快递配送"); order2.put("remarks", "注意保鲜"); // A程序接收订单请求并将其加入队列 redisTemplate.opsForList().leftPush(key6,order1); redisTemplate.opsForList().leftPush(key6,order2); // B程序从订单队列中获取订单数据并处理 System.out.println("处理订单:" + redisTemplate.opsForList().rightPop(key6));
@RedisHash:用于将Java对象映射到Redis的Hash数据结构中,使得对象的存储和检索变得更加简单
创建实体类
@Data @RedisHash public class User { @Id private Integer id; private String name; private Integer age; private String phone; }
创建接口,注意需要继承CrudRepository,这样改接口就具备对应实体的redis中的增删改查操作
public interface UserRedisMapper extends CrudRepository{ }
操作
@Autowired private UserRedisMapper userRedisMapper; @Test public void testRedisHash(){ User user = new User(); user.setId(100); user.setName("张三疯"); user.setAge(18); user.setPhone("19988889999"); // 保存 userRedisMapper.save(user); // 读取 User redisUser = userRedisMapper.findById(100).get(); System.out.println("redisUser:" + redisUser); // 更新 user.setPhone("18899998888"); userRedisMapper.save(user); // 删除 //userRedisMapper.deleteById(100); // 判断存在 boolean exists = userRedisMapper.existsById(100); System.out.println("exists: " + exists); }
Spring的缓存管理功能旨在帮助开发人员轻松地在应用程序中使用缓存,以提高性能和响应速度。它提供了一套注解和配置,使得开发人员可以在方法级别上进行缓存控制,并且支持多种缓存存储提供程序,如Caffeine、EhCache、Redis等。
注解 | 说明 |
---|---|
@Cacheable | 用于声明一个方法的返回值应该被缓存起来,以便下次相同的参数调用时可以直接返回缓存中的值,而不需要执行方法体。 |
@CachePut | 用于更新缓存中的数据,它会在方法执行后,将返回值更新到缓存中 |
@CacheEvict | 用于清除缓存中的数据,它可以根据条件清除指定的缓存项 |
准备表
CREATE TABLE product ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, price DECIMAL(10, 2) NOT NULL, stock INT NOT NULL );
INSERT INTO product (name, description, price, stock) VALUES ('iPhone 15', '最新的iPhone型号', 8999.99, 100), ('三星Galaxy S24', '旗舰安卓手机', 7899.99, 150), ('MacBook Pro', '专业人士的强大笔记本电脑', 15999.99, 50), ('iPad Air', '性能强劲的便携式平板电脑', 5599.99, 200), ('索尼PlayStation 6', '下一代游戏机', 4499.99, 75);
实体类
@Data @TableName public class Product { @TableId private Integer id; private String name; private String description; private Double price; private Integer stock; }
Mapper
public interface ProductMapper extends BaseMapper{ }
启动类添加注解 @MapperScan(“com.qqcn.*.mapper”)
Service
public interface ProductService { // 根据商品ID获取商品信息 Product getProductById(Integer id); // 添加新商品 Product addProduct(Product product); // 更新商品信息 Product updateProduct(Product product); // 根据商品ID删除商品 Integer deleteProductById(Integer id); }
@Service public class ProductServiceImpl implements ProductService { @Resource private ProductMapper productMapper; @Cacheable(value = "product", key = "'product:' + #id") @Override public Product getProductById(Integer id) { return productMapper.selectById(id); } @CachePut(value = "product", key = "'product:' + #product.id") @Override public Product addProduct(Product product) { productMapper.insert(product); return product; } @CachePut(value = "product", key = "'product:' + #product.id") @Override public Product updateProduct(Product product) { productMapper.updateById(product); return product; } @CacheEvict(value = "product", key = "'product:' + #id") @Override public Integer deleteProductById(Integer id) { productMapper.deleteById(id); return id; } }
测试
@Autowired private ProductService productService; @Test public void testQuery(){ Product product = productService.getProductById(1); System.out.println(product); } @Test public void testUpdate(){ Product product = productService.getProductById(1); System.out.println(product); product.setName("苹果19"); productService.updateProduct(product); System.out.println(productService.getProductById(1)); } @Test public void testDelete(){ productService.deleteProductById(1); }
以上就是本期分享内容,内容并不全面,旨在抛砖引玉,最重要的还是需要你到项目中,在合适的应用场景中去使用redis,发挥出redis的优势和价值。
上一篇:mysql中find