分布式session之token解决方案实现

基于令牌(Token)方式实现Session解决方案,因为Session本身就是分布式共享连接

用token代替session

废话不多说,看项目:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId> com.toov5.tokenSession</groupId>
  <artifactId>tokenSession</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<properties>
		<weixin-java-mp.version>2.8.0</weixin-java-mp.version>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.build.locales>zh_CN</project.build.locales>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<!-- <exclusions> <exclusion> <groupId>com.fasterxml.jackson.core</groupId> 
				<artifactId>jackson-databind</artifactId> </exclusion> </exclusions> -->
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
		<!-- Testing Dependencies -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
           <dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
		</dependency> 
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-pool2</artifactId>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<maimClass>com.meiteedu.WxMpApplication</maimClass>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>

			</plugin>
		</plugins>
	</build>
</project>

 yml

server:
  port: 8081
spring:
  redis:
    database: 0   
    host:  192.168.91.3
    port:  6379
    password:  123
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 10000
redis:
  hostname: 192.168.91.3     
  port:  6379
  password:  123

  redis

package com.toov5.service;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //这样该方法支持多种数据类 
    public void set(String key , Object object, Long time){
        if (object instanceof String ) {  //判断下是String类型�?
            String argString =(String)object;  //强转�?
            //存放String类型
            stringRedisTemplate.opsForValue().set(key, argString);
        }
        //如果存放Set类型
        if (object instanceof Set) {
            Set<String> valueSet =(Set<String>)object;
            for(String string:valueSet){
                stringRedisTemplate.opsForSet().add(key, string);  //此处点击下源码看 第二个参数可以放好多
            }
        }
        //设置有效�
        if (time != null) {
            stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
        
    }
    //做个封装
    public void setString(String key, Object object){
        String argString =(String)object;  //强转
        //存放String类型
        stringRedisTemplate.opsForValue().set(key, argString);
    }
    public void setSet(String key, Object object){
        Set<String> valueSet =(Set<String>)object;
        for(String string:valueSet){
            stringRedisTemplate.opsForSet().add(key, string);  //此处点击下源码看 第二个参数可以放好多
        }
    }
    
    public String getString(String key){
     return    stringRedisTemplate.opsForValue().get(key);
    }
    
    
}

token的封装

package com.toov5.service;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.qos.logback.core.subst.Token;

@Service
public class TokenService {
     @Autowired
    private RedisService redisService;
    
    
    // 1 使用token方式替代session功能
    //存入和获取
    public  String put(Object value){
        //判断您是否为空
        if (value == null) {
            return null;
        }
        // 先生成对应的token(token 实际上等于key)
        String token = getToken();
        //存入在redis中
        redisService.setString(token, value);
        //直接返回对应的token
        
        return token;
    }
    
    public String get(String token){
      return redisService.getString(token);        
    }
    

  public String getToken(){
      return UUID.randomUUID().toString();
  }
    
}

controller

package com.toov5.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.toov5.service.TokenService;

@RestController
public class TestTokenController {

    @Autowired
    private TokenService tokenService;
    
    //使用token方式替代session     sessiong服务器端创session 返回sessionid
    @RequestMapping("/put")
    public String put(String value){
         String string = tokenService.put(value);
         System.out.println(string);
        return string;
    }
    //生成好的token如何存放? 移动端存放本地文件  浏览器cookie
    
    
    @RequestMapping("/get")
    public String get(String object){
        return tokenService.get(object);
    }
    
    //http如何传递? 放在请求头里面  最好建议请求头里面
    
    
    
     
}

运行访问

怎么刷新都能获取到哦

 

redis 在服务器集群的时候 分布式缓存可以共享

 

 

 

posted @ 2018-11-04 16:08  toov5  阅读(7449)  评论(0编辑  收藏  举报