栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java整合redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java整合redis

Jedis

官方客户端,类似于 JDBC,可以看做是对 redis 命令的包装。

基于 BIO,线程不安全,需要配置连接池管理连接。

Lettuce

目前主流推荐的驱动,基于 Netty NIO,API 线程安全 (springboot 默认推荐使用)

Redission

基于 Netty NIO,API 线程安全。 亮点:大量丰富的分布式功能特性,比如 JUC 的线程安全集合和工具的分布式版本,分布式的基 本数据类型和锁等。

redis于spring的整合 Spring Data Redis

核心是 RedisTemplate(可以配置基于 Jedis,Lettuce,Redisson)) 使用方式类似于 MongoDBTemplate,JDBCTemplate 或 JPA

 

spring Boot 与 Redis 集成

引入 spring-boot-starter-data-redis 配置 spring redis

Spring Cache 与 Redis 集成

默认使用全局的 CacheManager 自动集成 使用 ConcurrentHashMap 或 ehcache 时,不需要考虑序列化问题 (因为本身就是在jvm)。

redis 的话,需要:

1、默认使用 java 的对象序列化,对象需要实现 Serializable

2、自定义配置,可以修改为其他序列化方式

MyBatis 项目集成 cache 示例

1、集成 spring boot 与 mybatis,实现简单单表操作,配置成 rest 接口

2、配置 ehcache+mybatis 集成,实现 mybatis 二级缓存 (命中二级缓存 就不需要访问数据库了 直接就是在mybatis ORM层就返回了)

开启二级缓存代码




配置ehcache文件



    
    
    
        
        
​
        
        
    

3、配置 spring cache+ehcache 缓存,实现方法级别缓存 (在service层放上加上缓存数据,当我们Controller 调用service 当service 没有被修改过 已经被spring cache 缓存了 就不会到 更下面 orm层! 实现更高效的缓存 )

@CacheConfig(cacheNames = "users")
public interface UserService {
​
    User find(int id);
​
    List list();
​
}
spring:
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
  cache:
    type: redis
  redis:
    host: localhost
    lettuce:
      pool:
        max-active: 16
        max-wait: 10ms
@SpringBootApplication(scanBasePackages = "io.kimmking.cache")
@MapperScan("io.kimmking.cache.mapper")
@EnableCaching
public class CacheApplication {
​
   public static void main(String[] args) {
      SpringApplication.run(CacheApplication.class, args);
   }
​
}
@Service
public class UserServiceImpl implements UserService {
​
    @Autowired
    UserMapper userMapper; //DAO  // Repository
​
    // 开启spring cache
    @Cacheable(key="#id",value="userCache")
    public User find(int id) {
        System.out.println(" ==> find " + id);
        return userMapper.find(id);
    }
​
    // 开启spring cache
    @Cacheable //(key="methodName",value="userCache")
    public List list(){
        return userMapper.list();
    }
​
}

4、修改 spring cache 使用 redis 远程缓存代替 ehcache 本地缓存

package io.kimmking.cache;
​
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
​
import javax.annotation.Resource;
​
import static org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig;
​
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
​
    @Resource
    private RedisConnectionFactory factory;
​
    
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return (o, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(o.getClass().getName()).append(".");
            sb.append(method.getName()).append(".");
            for (Object obj : objects) {
                sb.append(obj.toString()).append(".");
            }
            //System.out.println("keyGenerator=" + sb.toString());
            return sb.toString();
        };
    }
​
    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
​
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
​
        redisTemplate.setKeySerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
​
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    }
​
    @Bean
    @Override
    public CacheResolver cacheResolver() {
        return new SimpleCacheResolver(cacheManager());
    }
​
    @Bean
    @Override
    public CacheErrorHandler errorHandler() {
        // 用于捕获从Cache中进行CRUD时的异常的回调处理器。
        return new SimpleCacheErrorHandler();
    }
​
    @Bean
    @Override
    public CacheManager cacheManager() {
        RedisCacheConfiguration cacheConfiguration =
                defaultCacheConfig()
                        .disableCachingNullValues()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }
}

5、修改 spring cache 使用 jackson json 序列化代替 java 序列化

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/888747.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号