spring-boot-starter-redis 集成

时间:2025-03-22 07:23:16

redis支持

代码块

<!-- /artifact//spring-boot-starter-redis -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.0.</version>
</dependency>

更多支持

/artifact//spring-boot-starter-redis

redis配置

# REDIS (RedisProperties)  
spring.redis.database= # database name  
spring.redis.host=localhost # server host  
spring.redis.password= # server password  
spring.redis.port=6379 # connection port  
spring.redis.pool.max-idle=8 # pool settings ...  
spring.redis.pool.min-idle=0  
spring.redis.pool.max-active=8  
spring.redis.pool.max-wait=-1  
spring.redis.sentinel.master= # name of Redis server  
spring.redis.sentinel.nodes= # comma-separated list of host:port pairs  

JAVA代码

package ;

import org.;
import org.;
import ;
import ;
import ;
import ;

/**
 * redis
 * 
 *
 * @email h_anke@
 * @create 2017-03-06 13:57
 **/
@Component
public class RedisBusiness {

    private static final Logger logger = ();

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    public void setEx(String key, String value , int expire) throws Exception{
        RedisConnection connection = ();
        try {
            ((), expire, ());
        }catch (Exception e){
            ("redis 保存数据出现情况,现发起一次重复连接", e);
            if (connection != null)
                ();
            connection = ();
            ((), expire, ());
        }finally {
            if (connection != null)
                ();
        }
    }

    public void del(String key) throws Exception{
        RedisConnection connection = ();
        try {
            (());
        } finally {
            if (connection != null)
                ();
        }
    }

    public String get(String key) throws Exception{
        RedisConnection connection = ();
        byte[] bytes = null;
        try {
            bytes = (());
        }finally {
            if (connection != null)
                ();
        }
        if (bytes == null) {
            ("redis缓存无此key,可能是超时失效了");
            throw new Exception("redis 失效");
        }
        return  new String(bytes);
    }

    public void set(String key,String value) throws Exception{
        RedisConnection connection = ();
        try {
            ((), ());
        }finally {
            if (connection != null)
                ();
        }
    }

}