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

企业门户网站功能百度账号登录不了

企业门户网站功能,百度账号登录不了,ui设计尺寸规范,免费软件下载大全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/499263.html

相关文章:

  • wordpress站点标题删除必应bing搜索引擎
  • 新闻网站怎么备案营销网站建设规划
  • 最好的网站模板国内搜索网站排名
  • 有个蓝色章鱼做标志的网站seo是干什么的
  • 建设购物网站需要多少费用每日新闻摘抄10一30字
  • 廊坊营销网站团队seo关键词布局
  • 网站被host重定向是什么意思百度新闻网页
  • 网站建设一龙条如何在网上推广自己
  • wordpress建站教程第六节交换友情链接推广法
  • 湖北营销型网站建设价格怎么制作自己的个人网站
  • 新媒体营销的概念是什么宁波seo外包推广排名
  • 网站备案收费标准网站建设是什么
  • 给自己的网站起名字图片搜索
  • 长沙市做网站的网页广告怎么做
  • 做网站诈钱深圳网络推广软件
  • 做网站大网络推广文案
  • 企业产品网站模板苏州seo关键词优化排名
  • 聊城做企业网站百度推广开户
  • 家具网站建设的前景分析百度信息
  • 网站建设 镇江网络推广员工作内容
  • 长沙学做网站建设关键词排名优化软件价格
  • 常德做网站多少钱在线培训平台哪家好
  • 学校微网站模板下载地址seo快速排名关键词
  • 网址域名ip排名优化
  • wordpress友情链接函数天津seo推广软件
  • 兴平网站开发百度移动排名优化软件
  • 政府网站建设和使用带来哪些积极的影响优化大师win10下载
  • 西昌市做网站的谷歌三件套一键安装
  • 网页设计实验报告遇到的问题西安关键词优化软件
  • 模板网pi企业网站seo推广