1. 程式人生 > >SpringBoot+MyBatis+Redis實現SSO單點登入系統(二)

SpringBoot+MyBatis+Redis實現SSO單點登入系統(二)

SpringBoot+MyBatis+Redis實現SSO單點登入系統(二)

 

三、程式碼

配置檔案配置資料庫,redis等相關的資訊。

# See http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# Thymeleaf配置
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
spring.main.show-banner=false
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
logging.level.jdbc=OFF
logging.level.jdbc.sqltiming=DEBUG
logging.level.jdbc.resultsettable=DEBUG
# 資料庫配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/taotao?useSSL=false
spring.datasource.username=root
spring.datasource.password=root

# 日誌配置
logging.config=classpath:logback-spring.xml
logging.level.root=info

# MyBatis配置
mybatis.type-aliases-package=cn.hzr0523.entity
mybatis.mapper-locations=classpath:mapper/*.xml

#Redis Cluster
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.maxTotal=30

USER_SESSION_KEY=REDIS_USER_SESSION
SSO_SESSION_EXPIRE=30

接著,是jedisConfig的配置,採用java配置方式,取代了xml配置,也是Spring Boot推薦的一種配置方式。

package cn.hzr0523.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisConfig {

    @Value("${spring.redis.maxTotal}")
    public Integer maxTotal;

    @Value("${spring.redis.host}")
    public String host;

    @Value("${spring.redis.port}")
    public Integer port;

    @Value("${spring.redis.password}")
    public String password;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        return jedisPoolConfig;
    }

    @Bean
    public JedisPool jedisPool() {
        JedisPool jedisPool = new JedisPool(jedisPoolConfig(), host, port, 30, password);
        return jedisPool;
    }
}

接下來jedis工具類的編碼:

package cn.hzr0523.service;
public interface JedisClient {
    String get(String key);
    String set(String key, String value);
    String hget(String hkey, String key);
    long hset(String hkey, String key, String value);
    long incr(String key);
    long expire(String key, int second);
    long ttl(String key);
    long del(String key);
    long hdel(String hkey, String key);
}
package cn.hzr0523.service.impl;

import cn.hzr0523.service.JedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 單個redis
 */
@Service
public class JedisClientSingle implements JedisClient {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public String get(String key) {
        Jedis jedis = jedisPool.getResource();
        String string = jedis.get(key);
        jedis.close();
        return string;
    }

    @Override
    public String set(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        String string = jedis.set(key, value);
        jedis.close();
        return string;
    }

    @Override
    public String hget(String hkey, String key) {
        Jedis jedis = jedisPool.getResource();
        String string = jedis.hget(hkey, key);
        jedis.close();
        return string;
    }

    @Override
    public long hset(String hkey, String key, String value) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.hset(hkey, key, value);
        jedis.close();
        return result;
    }

    @Override
    public long incr(String key) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.incr(key);
        jedis.close();
        return result;
    }

    @Override
    public long expire(String key, int second) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.expire(key, second);
        jedis.close();
        return result;
    }

    @Override
    public long ttl(String key) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.ttl(key);
        jedis.close();
        return result;
    }

    @Override
    public long del(String key) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.del(key);
        jedis.close();
        return result;
    }

    @Override
    public long hdel(String hkey, String key) {
        Jedis jedis = jedisPool.getResource();
        Long result = jedis.hdel(hkey, key);
        jedis.close();
        return result;
    }
}

接下來就可以使用redis了

public ResultObject userLogin(UserDTO userDTO, HttpServletRequest request, HttpServletResponse response) {
        ResultObject resultObject = new ResultObject();
        if (userDTO == null) {
            resultObject.setResultCode("0");
            resultObject.setResultMessage("引數錯誤");
            return resultObject;
        }
        //根據登入資訊查詢學員資訊
        TbUser user = userMapper.getUserInfo(userDTO.getUserName(), userDTO.getPassword());
        if (user == null) {
            resultObject.setResultCode("0");
            resultObject.setResultMessage("使用者名稱或密碼錯誤");
            return resultObject;
        }
        //登入成功,把使用者資訊寫入redis
        //String s = jedisClientSingle.get(USER_SESSION_KEY);
        //logger.info("USER_SESSION_KEY: " + s);
        //生成一個使用者token
        String token = UUID.randomUUID().toString();
        logger.info(JSONObject.toJSONString(user));
        jedisClient.set(USER_SESSION_KEY + ":" + token, JSONObject.toJSONString(user));
        //設定session過期時間
        jedisClient.expire(USER_SESSION_KEY + ":" + token, SSO_SESSION_EXPIRE);
        //新增寫cookie的邏輯,cookie的有效期是關閉瀏覽器就失效。
        CookieUtils.setCookie(response, "TT_TOKEN", token, -1);
        //返回token
        resultObject.setResultCode("1");
        resultObject.setResultMessage("登入成功");
        resultObject.setResultData(token);
        return resultObject;
    }

簡單小demo,也是參考別人寫的,在編寫過程中也遇到了一些問題,包括redis的安裝,jedis的使用。有錯才能成長,大家一起進步。