java spring中使用redis

pom文件下添加配置:

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.2</version>
        </dependency>

        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.0.8</version>
        </dependency>

        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.0.8</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

application.yml中配置redis连接信息(根据自己的redis服务器进行更改):

spring:
  redis:
    lettuce:
      pool:
        MaxTotal: 400
        minIdle: 1
        maxWaitMillis: 5000
        maxIdle: 30
        testOnBorrow: true
        testOnReturn: true
        testWhileIdle: true

redis:
  database: 1
  hostName: 10.0.52.160
  password:
  port: 6379
  timeout: 5000

创建redis配置类:

/**
 * redis配置
 */
@Data
@Configuration
@ConfigurationProperties("redis")
public class RedisPoolConfig {

    private String hostName;
    private int port;
    private String password;
    private int database;
    private int timeout;

    @Bean
    @ConfigurationProperties(prefix = "spring.redis.lettuce.pool")
    @Scope(value = "prototype")
    public GenericObjectPoolConfig poolConfig() {
        return new GenericObjectPoolConfig();
    }

    @Bean
    @Primary
    public JedisPool jedisPoolDefault(GenericObjectPoolConfig poolConfig) {
        if (null != password && password.length() == 0) {
            password = null;
        }
        return new JedisPool(poolConfig, hostName, port, timeout, password, database);

    }

    @Bean(name = "recreationCoreRedisExecutor")
    @Primary
    public RedisExecutor redisExecutor(JedisPool jedisPoolDefault) {

        return new JedisExecutor(jedisPoolDefault);
    }
}

 

redis相关接口和执行器定义:

/**
 * jedis执行命令,有返回值
 */
public interface JedisCallable<T> {

    /**
     * 使用jedis连接执行redis命令
     *
     * @param instance
     * @return
     * @throws Exception 业务异常可以自行处理
     */
    T call(Jedis instance) throws Exception;
}
/**
 * 使用jedis的pipleline执行redis命令
 */
public interface JedisPipelined {

    /**
     * 使用jedis pipeline批量执行一组redis命令
     * <p>
     * 注意:需要自己调用pipeline.sync()方法提交命令
     *
     * @param pipeline
     * @throws Exception 业务异常可以自行处理
     */
    void runInPipeline(Pipeline pipeline) throws Exception;
}
/**
 * jedis执行命令,不带返回值
 */
public interface JedisRunnable {

    /**
     * 使用jedis连接执行redis命令
     *
     * @param instance
     * @throws Exception 业务异常可以自行处理
     */
    void run(Jedis instance) throws Exception;
}
/**
 * Redis执行器
 */
public interface RedisExecutor {

    /**
     * 使用jedis执行redis命令
     */
    void doInRedis(JedisRunnable runnable);

    /**
     * 使用jedis执行redis命令
     */
    <T> T doInRedis(JedisCallable<T> callable);

    /**
     * 使用jedis pipeline机制批量执行redis命令
     * <p>
     * 请使用pipeline.sync()方法提交批量执行
     * <p>
     */
    void doInPipeline(JedisPipelined pipeline);
}

/**
 * Jedis执行器,用来执行与Redis相关的业务逻辑
 * <p>
 * 业务逻辑由业务模块来写,这里只负责执行,包括异常的处理,Redis连接的分配与回收
 */
public class JedisExecutor implements RedisExecutor {

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

    private JedisPool jedisPool;

    public JedisExecutor(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    private Jedis getJedis(JedisPool jedisPool) {
        Jedis resource;
        try {
            resource = jedisPool.getResource();
        } catch (JedisException e) {
            logger.error("从连接池中拿Jedis连接时发生异常", e);
            throw e;
        }
        if (resource == null) {
            logger.error("从连接池中拿Jedis连接为空");
            throw new IllegalStateException("从连接池中拿Jedis连接为空");
        }
        return resource;
    }

    private void finishResource(JedisPool jedisPool, Jedis resource) {
        if (jedisPool == null) {
            return;
        }
        resource.close();
    }

    private void logResourceInfo(Jedis resource) {
        StringBuilder message = new StringBuilder();
        message.append("Redis连接属性,host ip:");
        message.append(resource.getClient().getHost());
        message.append(",port:");
        message.append(resource.getClient().getPort());
        message.append(",DB:");
        message.append(resource.getDB());
        message.append(",ConnectionTimeout:");
        message.append(resource.getClient().getConnectionTimeout());
        message.append(",SoTimeout:");
        message.append(resource.getClient().getSoTimeout());
        logger.debug(message.toString());
    }

    @Override
    public void doInRedis(JedisRunnable runnable) {
        Jedis jedis = getJedis(jedisPool);
        try {
            logResourceInfo(jedis);
            runnable.run(jedis);
        } catch (Exception e) {
            // 处理业务异常
            throw new RedisRuntimeException(e);
        } finally {
            // 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
            finishResource(jedisPool, jedis);
        }
    }

    @Override
    public <T> T doInRedis(JedisCallable<T> callable) {
        Jedis jedis = getJedis(jedisPool);
        try {
            logResourceInfo(jedis);
            return callable.call(jedis);
        } catch (Exception e) {
            // 处理业务异常
            throw new RedisRuntimeException(e);
        } finally {
            // 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
            finishResource(jedisPool, jedis);
        }
    }

    @Override
    public void doInPipeline(JedisPipelined pipelined) {
        Jedis jedis = getJedis(jedisPool);
        try {
            logResourceInfo(jedis);
            Pipeline pipeline = jedis.pipelined();
            pipelined.runInPipeline(pipeline);
        } catch (Exception e) {
            // 处理业务异常
            throw new RedisRuntimeException(e);
        } finally {
            // 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
            finishResource(jedisPool, jedis);
        }
    }
}
/**
 * redis运行时异常
 */
public class RedisRuntimeException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public RedisRuntimeException() {
		super();
	}

	public RedisRuntimeException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public RedisRuntimeException(String message, Throwable cause) {
		super(message, cause);
	}

	public RedisRuntimeException(String message) {
		super(message);
	}

	public RedisRuntimeException(Throwable cause) {
		super(cause);
	}

}

创建测试控制器:

/**
 * 测试Controller
 *
 * @author tuc
 */
@RestController
public class TestController {


    @Autowired
    private UserCache userCache;

    /***
     * 保存用户信息到redis(假设用户id=1)
     */
    @PostMapping("/setCache")
    public ResultModel setCache() {
        try {
            Map<String, Object> map = new HashMap<>(1);
            UserModel user = new UserModel();
            user.setId(1);
            user.setName("张三");
            user.setAge(18);
            user.setPhone("15388888888");
            userCache.cacheUserRecord(user);
            map.put("user", user);
            return ResultTools.result(0, "", map);
        } catch (Exception e) {
            return ResultTools.result(404, e.getMessage(), null);
        }
    }

    /***
     * 获取redis中缓存的用户信息
     */
    @GetMapping("/getCache")
    public ResultModel getCache(Integer id) {
        try {
            Map<String, Object> map = new HashMap<>(1);
            UserModel user = userCache.getUserRecord("" + id);
            map.put("user", user);
            return ResultTools.result(0, "", map);
        } catch (Exception e) {
            return ResultTools.result(404, e.getMessage(), null);
        }
    }

    /***
     * 删除对应缓存
     */
    @PostMapping("/delCache")
    public ResultModel delCache(Integer id) {
        try {
            Map<String, Object> map = new HashMap<>(1);
            userCache.delUserRecord(id + "");
            return ResultTools.result(0, "", map);
        } catch (Exception e) {
            return ResultTools.result(404, e.getMessage(), null);
        }
    }


}

调用http://localhost:8080/setCache

使用redis可视化工具查看:

可以看到数据已经存进redis中了

调用http://localhost:8080/getCache?id=1:

可以看到,正常取到了redis中对应id为1的值了

想手动删除的时候调用http://localhost:8080/delCache?id=1:

使用redis可视化工具查看:

缓存的id=1的用户信息已被删除掉了。

最后附上源码下载地址:https://download.youkuaiyun.com/download/qq_29370483/11194881

 

 

 

Spring Cache中,你可以利用Redis作为缓存存储,并通过Redis的TTL(Time To Live,生存时间)特性来设置缓存数据的过期时间。首先,你需要在Spring Boot中配置Redis支持,然后在Spring Cache中创建一个`CacheManager`实例,指定Redis缓存。 以下是一个简单的步骤: 1. 添加依赖:在你的`pom.xml`文件中添加Spring Data RedisSpring Boot Actuator的依赖,例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> ``` 2. 配置Redis:在`application.properties`或`application.yml`中设置Redis的相关连接信息: ```properties spring.redis.host=your-redis-host spring.redis.port=6379 spring.redis.database=0 ``` 3. 创建`CacheManager`:在Spring Boot的主类上添加`@EnableCaching`注解,然后注入`RedisCacheManager`: ```java @EnableCaching public class Application { private static final String DEFAULT_CACHE_NAME = "myCache"; @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { SimpleCacheConfig config = new SimpleCacheConfig(); config.setExpireAfterWriteSeconds(30); // 设置默认的过期时间为30秒 return new RedisCacheManager(factory, DEFAULT_CACHE_NAME, config); } } ``` 4. 使用Cache:在需要缓存的service或repository中,直接使用`@Cacheable`或`@CacheEvict`注解操作缓存,如: ```java @Service @Cacheable(value = DEFAULT_CACHE_NAME, key = "#id") public MyEntity loadFromDatabase(Long id) { // 从数据库加载实体 } @CacheEvict(value = DEFAULT_CACHE_NAME, key = "#id") public void updateMyEntity(MyEntity entity) { // 更新数据库并移除对应缓存 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值