Redis+spring boot

1.配置文件:

redis:
    database: 0
    host: //redisIp
    port: 16376
    password: ifValue@QA-Redis888@666
    timeout: 30000
    pool:
      max-active: 50
      max-wait: 1000
      max-idle: 10
      min-idle: 10

2.Config类配置:

package com.ftvalue.sso.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableAutoConfiguration
@Slf4j
public class RedisConfig {

	@Value("${spring.redis.pool.max-active}")
    Integer maxActive;
    @Value("${spring.redis.pool.max-idle}")
    Integer maxIdle;
    @Value("${spring.redis.pool.max-wait}")
    Integer maxWait;
    @Value("${spring.redis.pool.min-idle}")
    Integer minIdle;
    @Value("${spring.redis.host}")
    String hostname;
    @Value("${spring.redis.password}")
    String password;
    @Value("${spring.redis.port}")
    String port;
    @Value("${spring.redis.database}")
    String database;
    @Value("${spring.redis.timeout}")
    String timeout;

	@Bean
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
		config.setMaxWaitMillis(maxWait);
        return config;
    }

    @Bean
    public JedisConnectionFactory getConnectionFactory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        factory.setHostName(hostname);
        factory.setPassword(password);
        factory.setPort(Integer.parseInt(port));
        factory.setDatabase(Integer.parseInt(database));
        factory.setTimeout(Integer.parseInt(timeout));
        log.info("JedisConnectionFactory bean init success.");
        return factory;
    }


    @Bean
    public RedisTemplate<String, Object> getRedisTemplate(){
    	RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
    	template.setConnectionFactory(getConnectionFactory());
    	template.setKeySerializer(template.getStringSerializer());
    	template.setValueSerializer(template.getStringSerializer());
    	template.setHashKeySerializer(template.getStringSerializer());
    	template.setHashValueSerializer(template.getStringSerializer());
        return template;
    }
}

3.RedisUtilServiceImpl

package com.ftvalue.sso.service.impl;

import com.alibaba.fastjson.JSON;
import com.ftvalue.sso.service.IRedisUtilService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author hackerli
 */
@Service
public class RedisUtilServiceImpl implements IRedisUtilService {

    private static Logger logger = LoggerFactory.getLogger(RedisUtilServiceImpl.class.getName());

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean set(final String key, final String value) {
        try{
            ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
            valueOps.set(key, value);
            return true;
        }catch (Exception e) {
            logger.info("push string to redis error == [{}]", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean increment(String key, String value) {
        redisTemplate.opsForValue().increment(key, new Long(value != null?value:"0"));
        return false;
    }

    @Override
    public boolean set(String key, String value, long expireTime,final TimeUnit unit) {
        try{
            ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
            valueOps.set(key, value,expireTime,unit);
            return true;
        }catch (Exception e) {
            logger.info("push string to redis error == [{}]", e.getMessage());
            return false;
        }
    }

    @Override
    public String get(final String key){
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    @Override
    public boolean expire(final String key, long expire,TimeUnit unit) {
        return redisTemplate.expire(key, expire, unit);
    }

    @Override
    public <T> boolean setList(String key, List<T> list) {
        String value = JSON.toJSONString(list);
        return set(key,value);
    }

    @Override
    public <T> List<T> getList(String key,Class<T> clz) {
        String json = get(key);
        if(json!=null){
            List<T> list = JSON.parseArray(json,clz);
            return list;
        }
        return null;
    }

    @Override
    public long lpush(final String key, Object obj) {
        String value = JSON.toJSONString(obj);
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        long count = lops.leftPush(key,value);
        return count;
    }

    @Override
    public long rpush(String key, Object obj) {
        String value = JSON.toJSONString(obj);
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        long count = lops.rightPush(key,value);
        return count;
    }

    @Override
    public <T> T lpop(String key,Class<T> clz) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        String value = (String) lops.rightPop(key);
        T t = JSON.parseObject(value, clz);
        return t;
    }

    @Override
    public <T> T rpop(String key, Class<T> clz) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        //String value = (String) lops.rightPop(key);
        String value = (String)lops.rightPop(key,100,TimeUnit.MILLISECONDS);
        T t = JSON.parseObject(value, clz);
        return t;
    }

    @Override
    public long removeIndexList(String key, long i, Object obj) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        long result = lops.remove(key,i,obj);
        return result;
    }

    @Override
    public long setAdd(String key, Object obj) {
        String value = JSON.toJSONString(obj);
        SetOperations<String,Object> zops = redisTemplate.opsForSet();
        long count = zops.add(key,value);
        return count;
    }

    @Override
    public <T> T setPop(String key, Class<T> clz) {
        SetOperations<String,Object> zops = redisTemplate.opsForSet();
        String value = (String)zops.pop(key);
        T t = JSON.parseObject(value, clz);
        return t;
    }

    @Override
    public <T> List<T> getAllSet(String key, Class<T> clz) {
        SetOperations<String,Object> zops = redisTemplate.opsForSet();
        Set<Object> results = zops.members(key);
        if(results != null && results.size() > 0) {
            List<T> list = new ArrayList<>();
            for(Object result : results) {
                T t = JSON.parseObject((String)result, clz);
                list.add(t);
            }
            return list;
        }
        return null;
    }

    @Override
    public boolean zadd(String key, String value, double score) {
        ZSetOperations<String,Object> zSetOperations = redisTemplate.opsForZSet();
        boolean result = zSetOperations.add(key,value,score);
        return result;
    }

    @Override
    public Set<Object> zrank(String key, long start, long end, boolean flag) {
        ZSetOperations<String,Object> zSetOperations = redisTemplate.opsForZSet();
        //flag = true 表示正序
        Set<Object> set = null;
        if(flag) {
            set = zSetOperations.range(key,start,end);
        }else {
            set = zSetOperations.reverseRange(key,start,end);
        }
        return set;
    }

    @Override
    public long zsize(String key) {
        ZSetOperations<String,Object> zSetOperations = redisTemplate.opsForZSet();
        long size = zSetOperations.size(key);
        return size;
    }

    @Override
    public <T> List<T> getRangeList(String key, Class<T> clz) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        long length = lops.size(key);
        List<Object> results = lops.range(key,0,length);
        if(results != null && results.size() > 0) {
            List<T> list = new ArrayList<>();
            for(Object result : results) {
                T t = JSON.parseObject((String)result, clz);
                list.add(t);
            }
            return list;
        }
        return null;
    }

    @Override
    public <T> List<T> listRangeList(String key, long start, long end, Class<T> clz) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        List<Object> results = lops.range(key,start,end);
        if(results != null && results.size() > 0) {
            List<T> list = new ArrayList<>();
            for(Object result : results) {
                T t = JSON.parseObject((String)result, clz);
                list.add(t);
            }
            return list;
        }
        return null;
    }

    @Override
    public <T> T getIndexObject(String key, long index,Class<T> clz) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        Object result = lops.index(key,index);
        T t = JSON.parseObject((String)result, clz);
        return t;
    }

    @Override
    public long getListIndex(String key) {
        return redisTemplate.boundValueOps(key).increment(1l);
    }

    @Override
    public long listLength(String key) {
        ListOperations<String,Object> lops = redisTemplate.opsForList();
        long length = lops.size(key);
        return length;
    }

    @Override
    public boolean containsKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public boolean existHashKey(String key, String hashKey) {
        HashOperations<String,String,String> hops = redisTemplate.opsForHash();
        return hops.hasKey(key,hashKey);
    }

    @Override
    public void setObj(String key, Object object) {
        try{
            ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
            String value = JSON.toJSONString(object);
            valueOps.set(key, value);
        }catch (Exception e) {
            logger.info("push string to redis error == [{}]", e.getMessage());
        }
    }

    @Override
    public void setObj(String key, Object object, long timeout, TimeUnit unit) {
        try{
            ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
            String value = JSON.toJSONString(object);
            valueOps.set(key, value,timeout,unit);
        }catch (Exception e) {
            logger.info("push string to redis error == [{}]", e.getMessage());
        }
    }

    @Override
    public <T> T getObj(String key, Class<T> clz) {
        ValueOperations<String, Object> valueOps =  redisTemplate.opsForValue();
        String value = (String) valueOps.get(key);
        T t = JSON.parseObject(value, clz);
        return t;
    }

    @Override
    public boolean setHash(String key, String field, String value) {
        try{
            HashOperations<String,String,String> hops = redisTemplate.opsForHash();
            hops.put(key, field,value);
            return true;
        }catch (Exception e) {
            logger.info("push hash to redis error == [{}]", e);
            return false;
        }
    }

    @Override
    public <T> List<T> getHash(String key,Class<T> clz) {
        HashOperations<String,String,String> hops = redisTemplate.opsForHash();
        List<String> list = hops.values(key);
        List<T> results = new ArrayList<T>();
        if(list != null && list.size() > 0) {
            for(String l : list) {
                T t = JSON.parseObject(l, clz);
                results.add(t);
            }
        }
        return results;
    }

    @Override
    public boolean setAllHash(String key, Map<String, String> map) {
        HashOperations<String,String,String> hops = redisTemplate.opsForHash();
        hops.putAll(key, map);
        return true;
    }

    public boolean removeKey(String key, String hashKey) {
        try{
            HashOperations<String,String,String> hops = redisTemplate.opsForHash();
            hops.delete(key, hashKey);
            return true;
        }catch (Exception e) {
            logger.info("remove key from redis request key is [{}],hashKey is [{}]", key,hashKey);
            logger.info("remove key from redis error == [{}]", e);
            return false;
        }
    }

    @Override
    public <T> T getKey(String key, String hashKey, Class<T> clz) {
        try{
            HashOperations<String,String,String> hops = redisTemplate.opsForHash();
            String value = hops.get(key, hashKey);
            T t = JSON.parseObject(value, clz);
            return t;
        }catch (Exception e) {
            logger.info("remove key from redis request key is [{}],hashKey is [{}]", key,hashKey);
            logger.info("remove key from redis error == [{}]", e.getMessage());
            return null;
        }
    }

    @Override
    public void delKey(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void delKeys(Set<String> keys) {
        redisTemplate.delete(keys);
    }

    @Override
    public Set<String> getAllKeys(String pattern) {
        return redisTemplate.keys(pattern+ "*");
    }

    @Override
    public boolean lock(String key) {
        boolean result = redisTemplate.boundValueOps(key).setIfAbsent("1");
        redisTemplate.expire(key,3,TimeUnit.HOURS);
        return result;
    }

    @Override
    public boolean lock(String key, long timeout, TimeUnit timeUnit) {
        boolean result = redisTemplate.boundValueOps(key).setIfAbsent("1");
        redisTemplate.expire(key,timeout,timeUnit);
        return result;
    }

    @Override
    public void unlock(String key) {
        redisTemplate.delete(key);
    }

}

4.RedisServiceImpl

package com.ftvalue.sso.service.impl;import com.ftvalue.sso.repository.model.SysUserInfo;import com.ftvalue.sso.service.IRedisUtilService;import com.ftvalue.sso.service.RedisService;import com.ftvalue.sso.util.JsonUtil;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;/** * @author hackerli */@Service@Slf4jpublic class RedisServiceImpl implements RedisService { @Autowired IRedisUtilService iRedisUtilService;
//redis过期时间 @Value("${spring.redis.keyExpired:180}") Long expireTime;
//redis数据前缀 final static String USER_INFO_KEY = "sso:USER_INFO"; @Override public void setUserInfoToRedis(SysUserInfo sysUserInfo) { try { if(StringUtils.isNotBlank(sysUserInfo.getMobile())) { iRedisUtilService.set(USER_INFO_KEY + sysUserInfo.getMobile(), JsonUtil.toJson(sysUserInfo)); } if(StringUtils.isNotBlank(sysUserInfo.getLoginName())) { iRedisUtilService.set(USER_INFO_KEY + sysUserInfo.getLoginName(), JsonUtil.toJson(sysUserInfo)); } if(StringUtils.isNotBlank(sysUserInfo.getEmail())) { iRedisUtilService.set(USER_INFO_KEY + sysUserInfo.getEmail(), JsonUtil.toJson(sysUserInfo)); } }catch (Exception e){ log.error("保存用户信息入redis出错"); } } @Override public String getDataFromRedis(String loginName) { return iRedisUtilService.get(USER_INFO_KEY + loginName); } @Override public void updateDataToRedis(String loginName, String value) { iRedisUtilService.set(USER_INFO_KEY + loginName, value); }}

5.Controller类实现
package com.ftvalue.sso.service.impl;

import com.ftvalue.sso.constants.AppIpEnum;
import com.ftvalue.sso.constants.UserStatusEnum;
import com.ftvalue.sso.repository.mapper.SysUserInfoMapper;
import com.ftvalue.sso.repository.model.SysUserInfo;
import com.ftvalue.sso.response.ResultCode;
import com.ftvalue.sso.response.UserResponse;
import com.ftvalue.sso.service.IncrementNumber;
import com.ftvalue.sso.service.RedisService;
import com.ftvalue.sso.service.SysUserInfoService;
import com.ftvalue.sso.util.DateUtils;
import com.ftvalue.sso.util.JsonUtil;
import com.ftvalue.sso.util.MapBuilder;
import com.ftvalue.sso.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hackerli
 */
@Service
@Slf4j
public class SysUserInfoServiceImpl implements SysUserInfoService {
    private static final String LOGIN = "login";
    private static final String REGISTER = "register";
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IncrementNumber incrementNumber;
    @Value("${login.loginErrorTimes}")
    private Integer loginErrorTimes;
    @Value("${login.loginErrorRemind}")
    private Integer loginErrorRemind;
    @Override
    public UserResponse register(SysUserInfo sysUserInfo){
        UserResponse userResponse = new UserResponse();
        log.info("用户注册开始,用户名为:[{}],登陆用户名为:[{}]",sysUserInfo.getUserName(), sysUserInfo.getLoginName());
        try {
            SysUserInfo queryResultSysUserInfo = null;
            if(StringUtils.isBlank(sysUserInfo.getLoginName()) && StringUtils.isBlank(sysUserInfo.getMobile()) && StringUtils.isBlank(sysUserInfo.getEmail())){
                userResponse = new UserResponse(ResultCode.ERROR_REQUIRED.val(), ResultCode.ERROR_REQUIRED.msg());
                return userResponse;
            }
            queryResultSysUserInfo = validateSysUserInfoExits(sysUserInfo,userResponse, REGISTER);
            if(queryResultSysUserInfo != null && userResponse != null){
                return userResponse;
            }
            String userId = incrementNumber.getCurNo("user","%09d");
            if(StringUtils.isBlank(userId)){
                log.error("用户id生成为空");
                userResponse = new UserResponse(ResultCode.SYSTEM_ERROR.val(), ResultCode.SYSTEM_ERROR.msg());
                return userResponse;
            }
            sysUserInfo.setUserId(userId);
            sysUserInfo.setUserStatus(AppIpEnum.getStartStatus(sysUserInfo.getAppId()));
            sysUserInfo.setUserPwd(SHA1.encode(userId + sysUserInfo.getUserPwd()));
            initSysUserInfo(sysUserInfo);
            sysUserInfoMapper.insertSelective(sysUserInfo);
            redisService.setUserInfoToRedis(sysUserInfo);
            sysUserInfo.setUserPwd("");
            userResponse = new UserResponse(ResultCode.SUCCESS.val(), ResultCode.SUCCESS.msg());
            userResponse.setData(JsonUtil.toJson(sysUserInfo));
        }catch (Exception e){
            log.error("用户注册异常[{}],[{}]",e.getMessage(),e);
            userResponse = new UserResponse(ResultCode.SYSTEM_ERROR.val(), ResultCode.SYSTEM_ERROR.msg());
        }

        return userResponse;
    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

化猿和尚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值