当前位置: 首页 > wzjs >正文

在线免费网站建设平台做个网站

在线免费网站建设平台,做个网站,wordpress评论翻页,网站建设属于那个科目Spring Boot集成Redis:从配置到实战的完整指南Redis作为高性能的内存数据库,在现代应用开发中扮演着至关重要的角色。本文将详细讲解如何在Spring Boot项目中集成Redis,并提供多种使用场景的实战代码。一、为什么需要集成Redis? R…

Spring Boot集成Redis:从配置到实战的完整指南

Redis作为高性能的内存数据库,在现代应用开发中扮演着至关重要的角色。本文将详细讲解如何在Spring
Boot项目中集成Redis,并提供多种使用场景的实战代码。

一、为什么需要集成Redis?

Redis在Spring Boot应用中的核心价值:

  • 性能加速:将热点数据存入内存,访问速度比数据库快100倍

  • 解耦应用:作为独立的缓存层,减轻数据库压力

  • 丰富数据结构:支持字符串、哈希、列表、集合等高级数据结构

  • 分布式支持:实现分布式锁、会话共享等功能

  • 消息系统:提供发布/订阅模式实现异步通信

二、环境准备

  • JDK 17+

  • Spring Boot 3.2.0+

  • Redis 7.0+

三、快速集成Redis

1. 添加依赖

在pom.xml中添加Spring Data Redis和连接池依赖:

<dependencies><!-- Spring Data Redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 连接池 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><!-- JSON序列化 --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
</dependencies>

2. 配置Redis连接

在application.yml中添加配置:

spring:redis:host: 127.0.0.1port: 6379password: yourpassword # 无密码可省略database: 0 # 默认DBlettuce:pool:max-active: 20   # 最大连接数max-idle: 10     # 最大空闲连接min-idle: 5      # 最小空闲连接max-wait: 2000ms # 获取连接最大等待时间

3. 配置RedisTemplate

创建配置类解决键值序列化问题:

@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);// 使用Jackson序列化valueJackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);serializer.setObjectMapper(mapper);// 设置序列化template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);template.afterPropertiesSet();return template;}
}

四、Redis基础操作实战

1. 使用RedisTemplate操作

@Service
public class RedisService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;// 字符串操作public void setString(String key, String value) {redisTemplate.opsForValue().set(key, value);}public String getString(String key) {return (String) redisTemplate.opsForValue().get(key);}// 哈希操作public void setHash(String key, String field, Object value) {redisTemplate.opsForHash().put(key, field, value);}public Object getHash(String key, String field) {return redisTemplate.opsForHash().get(key, field);}// 设置过期时间public void setWithExpire(String key, Object value, long seconds) {redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);}// 删除键public Boolean delete(String key) {return redisTemplate.delete(key);}
}

2. 测试Controller

@RestController
@RequestMapping("/redis")
public class RedisController {@Autowiredprivate RedisService redisService;@PostMapping("/set")public String setValue(@RequestParam String key, @RequestParam String value) {redisService.setString(key, value);return "设置成功: " + key + "=" + value;}@GetMapping("/get/{key}")public String getValue(@PathVariable String key) {return "获取结果: " + redisService.getString(key);}@PostMapping("/setUser")public String setUser(@RequestParam String userId) {User user = new User(userId, "用户" + userId, "user" + userId + "@example.com");redisService.setHash("user:" + userId, "profile", user);return "用户信息已缓存";}@GetMapping("/getUser/{userId}")public User getUser(@PathVariable String userId) {return (User) redisService.getHash("user:" + userId, "profile");}// 用户实体类@Data@AllArgsConstructor@NoArgsConstructorstatic class User implements Serializable {private String id;private String name;private String email;}
}

五、Spring Cache集成Redis

1. 启用缓存支持

在启动类添加注解:

@SpringBootApplication
@EnableCaching // 启用缓存功能
public class RedisApplication {public static void main(String[] args) {SpringApplication.run(RedisApplication.class, args);}
}

2. 配置缓存管理器

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {@Autowiredprivate RedisConnectionFactory connectionFactory;@Beanpublic CacheManager cacheManager() {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)) // 默认过期时间.disableCachingNullValues() // 不缓存null.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).transactionAware().build();}
}

3. 使用缓存注解

@Service
public class ProductService {@Cacheable(value = "products", key = "#id")public Product getProductById(String id) {// 模拟数据库查询System.out.println("查询数据库: " + id);return new Product(id, "商品" + id, 99.99);}@CachePut(value = "products", key = "#product.id")public Product updateProduct(Product product) {// 模拟数据库更新System.out.println("更新数据库: " + product.getId());return product;}@CacheEvict(value = "products", key = "#id")public void deleteProduct(String id) {System.out.println("删除数据库记录: " + id);}// 条件缓存:只缓存价格大于100的商品@Cacheable(value = "expensiveProducts", key = "#id", condition = "#result.price > 100")public Product getProductWithCondition(String id) {return new Product(id, "高级商品", 199.99);}
}
http://www.dtcms.com/wzjs/180297.html

相关文章:

  • 商城网站建设流程怎么才能创建一个网站
  • 手机网站建设定制培训网络营销的机构
  • 建网站做点什么好南昌网站优化公司
  • 手机商城网站建设策划方案范文网络搜索引擎
  • 数码网站建设论文免费源码资源源码站
  • 做预算的网站附近电商培训班
  • 做公司网站需要提供的资料百度seo咋做
  • 网站优化哪里好网络seo推广培训
  • 珠海微网站哈尔滨优化网站公司
  • 乐陵seo排名企业网站优化解决方案
  • app软件免费模板下载网站成品网站源码1688免费推荐
  • 搭建网站教程网络推广员是干什么的
  • 余姚公司网站建设常州百度推广代理公司
  • 网站上如何做天气插件seo优化什么意思
  • 做网站的叫什么软件网店推广渠道有哪些
  • 专业做球赛旅游的网站足球排名世界排名
  • python 网站开发代码免费一键生成个人网站
  • 邛崃建设局网站seo关键词软件
  • 湖南建设厅网站外贸网站平台都有哪些 免费的
  • 谷城网站建设最近发生的热点新闻事件
  • 网站开发上市公司查收录网站
  • 涪城网站建设2022小说排行榜百度风云榜
  • 企业网站建设心得怎么收录网站
  • 定制一款appseo优化排名技术百度教程
  • 宠物网站建设毕业论文2022拉新推广赚钱的app
  • 苹果手机免费做ppt模板下载网站有哪些网站推广的作用
  • 招商外包服务公司保定seo网络推广
  • 东莞建外贸网站提高工作效率的句子
  • 网站建设方案备案内部优化
  • 网站管理 上传模板免费引流推广方法