iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >怎么在Spring Boot中利用Redis实现session共享
  • 384
分享到

怎么在Spring Boot中利用Redis实现session共享

springbootsessionredis 2023-05-30 23:05:46 384人浏览 泡泡鱼
摘要

本篇文章给大家分享的是有关怎么在Spring Boot中利用Redis实现session共享,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。引入spring-boot-start

本篇文章给大家分享的是有关怎么在Spring Boot中利用Redis实现session共享,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

引入spring-boot-starter-Redis,在pom.xml配置文件中增加配置如下(基于之前章节“Spring Boot 构建框架”中的pom.xml文件):

<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-redis</artifactId> </dependency>

可以注入一个自动配置的RedisConnectionFactory,StringRedisTemplate或普通的跟其他Spring Bean相同的RedisTemplate实例。默认情况下,这个实例将尝试使用localhost:6379连接Redis服务器

@Componentpublic class MyBean {  private StringRedisTemplate template;    @Autowired  public MyBean(StringRedisTemplate template) {    this.template = template;  }  // ...}

如果添加一个自己的任何自动配置类型的@Bean,它将替换默认的(除了RedisTemplate的情况,它是根据bean的名称'redisTemplate'而不是它的类型进行排除的)。如果在classpath路径下存在commons-pool2,默认会获得一个连接池工厂。

应用使用Redis案例

添加配置文件,配置内容如下:

# REDIS (RedisProperties)# Redis服务器地址spring.redis.host=192.168.0.58# Redis服务器连接端口spring.redis.port=6379 # 连接超时时间(毫秒)spring.redis.timeout=0

redis配置类,具体代码如下:

import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;  @Component @ConfigurationProperties(prefix = "spring.redis") public class RedisConn {      private String host;      private int port;      private int timeout;     public String getHost() {     return host;   }    public void setHost(String host) {     this.host = host;   }    public int getPort() {     return port;   }    public void setPort(int port) {     this.port = port;   }    public int getTimeout() {     return timeout;   }    public void setTimeout(int timeout) {     this.timeout = timeout;   }    @Override   public String toString() {     return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]";   }     }

注意:在RedisConn类中注解@ConfigurationProperties(prefix = "spring.Redis")的作用是读取SpringBoot的默认配置文件信息中以spring.redis开头的信息。

配置cache类

import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachinGConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JSONRedisSerializer; import org.springframework.stereotype.Component;  import com.cachemodle.RedisConn; import com.fasterxml.jackson.annotation.jsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper;    @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {    @Autowired   private RedisConn redisConn;          @Bean   @Override   public KeyGenerator keyGenerator() {     return new KeyGenerator() {        @Override       public Object generate(Object target, Method method, Object... params) {         StringBuilder sb = new StringBuilder();         sb.append(target.getClass().getName());         sb.append(method.getName());         for (Object obj : params) {           sb.append(obj.toString());         }         return sb.toString();       }     };    }        @SuppressWarnings("rawtypes")   @Bean   public CacheManager CacheManager(RedisTemplate redisTemplate) {     RedisCacheManager rcm = new RedisCacheManager(redisTemplate);     // 设置cache过期时间,时间单位是秒     rcm.setDefaultExpiration(60);     Map<String, Long> map = new HashMap<String, Long>();     map.put("test", 60L);     rcm.setExpires(map);     return rcm;   }          @Bean   public JedisConnectionFactory redisConnectionFactory() {     JedisConnectionFactory factory = new JedisConnectionFactory();     factory.setHostName(redisConn.getHost());     factory.setPort(redisConn.getPort());     factory.setTimeout(redisConn.getTimeout()); // 设置连接超时时间     return factory;   }       @SuppressWarnings({ "rawtypes", "unchecked" })   @Bean   public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {     StringRedisTemplate template = new StringRedisTemplate(factory);     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);     ObjectMapper om = new ObjectMapper();     om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);     om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);     jackson2JsonRedisSerializer.setObjectMapper(om);     template.setValueSerializer(jackson2JsonRedisSerializer);     template.afterPropertiesSet();     return template;   }  }

分析:缓存类继承的是CachingConfigurerSupport,它把读取的配置文件信息的RedisConn类对象注入到这个类中。在这个类中keyGenerator()方法是key的生成策略,CacheManager()方法是缓存管理策略,redisConnectionFactory()是redis连接,redisTemplate()方法是redisTemplate配置信息,配置后使redis中能存储Java对象。

测试配置是否成功,实例:

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class TestRedis {  @Autowired  private StringRedisTemplate stringRedisTemplate; // 处理字符串    @Autowired  private RedisTemplate redisTemplate; // 处理对象  @Test  public void test() throws Exception {    stringRedisTemplate.opsForValue().set("yoodb", "123");    Assert.assertEquals("123", stringRedisTemplate.opsForValue().get("yoodb"));  }}

简单封装的Redis工具类,代码如下:

import java.io.Serializable; import java.util.Set; import java.util.concurrent.TimeUnit;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component;  @Component public class RedisUtils {    @SuppressWarnings("rawtypes")   @Autowired   private RedisTemplate redisTemplate;       public void remove(final String... keys) {     for (String key : keys) {       remove(key);     }   }       @SuppressWarnings("unchecked")   public void removePattern(final String pattern) {     Set<Serializable> keys = redisTemplate.keys(pattern);     if (keys.size() > 0)       redisTemplate.delete(keys);   }       @SuppressWarnings("unchecked")   public void remove(final String key) {     if (exists(key)) {       redisTemplate.delete(key);     }   }       @SuppressWarnings("unchecked")   public boolean exists(final String key) {     return redisTemplate.hasKey(key);   }       @SuppressWarnings("unchecked")   public Object get(final String key) {     Object result = null;     ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();     result = operations.get(key);     return result;   }       @SuppressWarnings("unchecked")   public boolean set(final String key, Object value) {     boolean result = false;     try {       ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();       operations.set(key, value);       result = true;     } catch (Exception e) {       e.printStackTrace();     }     return result;   }       @SuppressWarnings("unchecked")   public boolean set(final String key, Object value, Long expireTime) {     boolean result = false;     try {       ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();       operations.set(key, value);       redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);       result = true;     } catch (Exception e) {       e.printStackTrace();     }     return result;   }  }

查询数据库时自动使用缓存,根据方法生成缓存,参考代码如下:

@Servicepublic class UserService { @Cacheable(value = "redis-key") public UserInfo getUserInfo(Long id, String sex, int age, String name) {   System.out.println("无缓存时调用----数据库查询");   return new UserInfo(id, sex, age, name); }}

注意:value的值就是缓存到redis中的key,此key是需要自己在进行增加缓存信息时定义的key,用于标识唯一性的。

Session 共享

分布式系统中session共享有很多不错的解决方案,其中托管到缓存中是比较常见的方案之一,下面利用Session-spring-session-data-redis实现session共享。

引入依赖,在pom.xml配置文件中增加如下内容:

<dependency>  <groupId>org.springframework.session</groupId>  <artifactId>spring-session-data-redis</artifactId></dependency>

Session配置,具体代码如下:

@Configuration@EnableRedishttpsession(maxInactiveIntervalInSeconds = 86400*30)public class SessionConfig {}

maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Spring Boot的server.session.timeout属性不再生效。

测试实例,具体代码如下:

@RequestMapping("uid")String uid(HttpSession session) {UUID uid = (UUID) session.getAttribute("uid");if (uid == null) {uid = UUID.randomUUID();}session.setAttribute("uid", uid);return session.getId();}

以上就是怎么在Spring Boot中利用Redis实现session共享,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注编程网精选频道。

--结束END--

本文标题: 怎么在Spring Boot中利用Redis实现session共享

本文链接: https://www.lsjlt.com/news/222009.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 怎么在Spring Boot中利用Redis实现session共享
    本篇文章给大家分享的是有关怎么在Spring Boot中利用Redis实现session共享,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。引入spring-boot-start...
    99+
    2023-05-30
    springboot session redis
  • spring boot与redis 实现session共享教程
    如果大家对spring boot不是很了解,大家可以参考下面两篇文章。Spring Boot 快速入门教程Spring Boot 快速入门指南这次带来的是spring boot + redis 实现session共享的教程。在spring ...
    99+
    2023-05-31
    spring boot redis
  • 在Spring-Session使用Redis如何实现共享session
    这期内容当中小编将会给大家带来有关在Spring-Session使用Redis如何实现共享session,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、添加依赖<dependency> &l...
    99+
    2023-05-31
    spring session redis
  • SpringBoot+SpringSession+Redis怎么实现session共享
    这篇文章主要介绍SpringBoot+SpringSession+Redis怎么实现session共享,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!springboot是什么springboot一种全新的编程规范,其...
    99+
    2023-06-14
  • Spring Boot项目利用Redis实现session管理实例
    在现代网络服务中,session(会话)不得不说是非常重要也是一定要实现的概念,因此在web后台开发中,对session的管理和维护是必须要实现的组件。这篇文章主要是介绍如何在Spring Boot项目中加入redis来实现对session...
    99+
    2023-05-31
    spring boot redis
  • Spring Boot中怎么利用Redis 实现缓存操作
    这期内容当中小编将会给大家带来有关Spring Boot中怎么利用Redis 实现缓存操作,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。一、缓存的应用场景二、更新缓存的策略三、运行 springboot-...
    99+
    2023-06-17
  • Spring Boot中怎么利用Redis实现分布式锁
    Spring Boot中怎么利用Redis实现分布式锁,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。分布式锁介绍Spring Boot 实现 Redis 分布式锁在 sprin...
    99+
    2023-06-16
  • 在SpringBoot中怎么使用Spring Session解决分布式会话共享问题
    本篇内容介绍了“在SpringBoot中怎么使用Spring Session解决分布式会话共享问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所...
    99+
    2023-06-16
  • 怎么利用vps实现文件共享
    要利用VPS实现文件共享,可以按照以下步骤进行操作:1. 首先,要确保你已经购买了一个VPS,并且已经成功连接到VPS的操作系统上。...
    99+
    2023-09-14
    vps
  • Oracle中怎么利用Openfiler实现共享存储
    这期内容当中小编将会给大家带来有关Oracle中怎么利用Openfiler实现共享存储,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、root用户,rac1、rac2关...
    99+
    2022-10-18
  • Spring Boot中怎么利用MybatisPlus实现逆向工程
    这篇文章将为大家详细讲解有关Spring Boot中怎么利用MybatisPlus实现逆向工程,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。 一、创建表  我们先创建数据库表:sys_log...
    99+
    2023-06-20
  • Spring Boot 中怎么利用JSR303 实现参数验证
    今天就跟大家聊聊有关Spring Boot 中怎么利用JSR303 实现参数验证,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。Bean Validation 规范内嵌的约束注解实例基...
    99+
    2023-06-05
  • 在Spring Boot中使用注解如何实现Redis 缓存
    在Spring Boot中使用注解如何实现Redis 缓存?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。一、创建 Caching 配置类RedisKeys.Javapackag...
    99+
    2023-05-31
    springboot redis 注解
  • 怎么在Spring boot中利用validation进行校验
    这篇文章主要为大家详细介绍了怎么在Spring boot中利用validation进行校验,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:前言接触springboot一年多,是时候摆脱这种校验方式了233 ,每...
    99+
    2023-06-06
  • 怎么在Spring Boot中利用ajax上传图片
    本篇文章给大家分享的是有关怎么在Spring Boot中利用ajax上传图片,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。启动类中加入SpringBoot重写addResour...
    99+
    2023-06-08
  • Spring Boot中怎么利用JUnit 5实现单元测试
    这篇文章给大家介绍Spring Boot中怎么利用JUnit 5实现单元测试,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1. 忽略测试用例执行JUnit 4:@Test  @Ignore ...
    99+
    2023-06-16
  • Ubuntu中怎么利用路由实现网络共享功能
    Ubuntu中怎么利用路由实现网络共享功能,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。  Ubuntu路由实现 Mac OS X 10.6 共享上网 route...
    99+
    2023-06-16
  • Redis通过在Spring Boot项目中使用实现集中式缓存
    这篇文章将为大家详细讲解有关Redis通过在Spring Boot项目中使用实现集中式缓存,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。 利用Spring Initializr来新建一个sp...
    99+
    2023-05-31
    springboot 集中 redis
  • node中怎么利用进程通信实现Cluster共享内存
    node中怎么利用进程通信实现Cluster共享内存,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。##IPC的基本用法:// w...
    99+
    2022-10-19
  • 如何在spring boot中利用mybatis实现多数据源切换
    今天就跟大家聊聊有关如何在spring boot中利用mybatis实现多数据源切换,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1.首先定义一个注解类@Retention(Rete...
    99+
    2023-05-31
    springboot mybatis 多数据源切换
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作