SpringBoot -- 集成Redis/CacheManager

               

前置工作

  • 了解Redis、Cache
  • spring-data-redis

Demo

引入 spring-data-Redis

build.gradle

compile ('org.springframework.data:spring-data-redis')compile ('redis.clients:jedis')
  • 1
  • 2
  • 1
  • 2

创建 RedisConfig,与Spring Cache进行集成;

  • 与Spring Cache进行集成时需要key、value的 序列化,不然会出现 \xAC\xED\x00\x05t\x00\x06之类的
  • 与Spring Cache集成后redis key会存入 cachekey+~keys中 xxx~keys

RedisConfig.Java

/** * @author cwenao * @version $Id RedisConfig.java, v 0.1 2017-01-29 15:17 cwenao Exp $$ */@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport{    @Bean(name="redisTemplate")    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {        RedisTemplate<String, String> template = new RedisTemplate<>();        RedisSerializer<String> redisSerializer = new StringRedisSerializer();        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);        ObjectMapper om = new ObjectMapper();        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);        jackson2JsonRedisSerializer.setObjectMapper(om);        template.setConnectionFactory(factory);        //key序列化方式        template.setKeySerializer(redisSerializer);        //value序列化        template.setValueSerializer(jackson2JsonRedisSerializer);        //value hashmap序列化        template.setHashValueSerializer(jackson2JsonRedisSerializer);        return template;    }    @Bean    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate) {        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);        cacheManager.setDefaultExpiration(3000);        return cacheManager;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

配置 redis连接信息,redis启用了密钥

application.yml

Spring:  redis:    host: 127.0.0.1    port: 6379    password: 111222333444555666    timeout: 5000    pool:      max-idle: 8      min-idle: 0      max-active: 8      max-wait: -1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

创建 Cache 操作类

/** * @author cwenao * @version $Id AbstractCacheSupport.java, v 0.1 2017-01-29 15:35 cwenao Exp $$ */public abstract class AbstractCacheSupport {    /**     * 获取缓存内容     * @param cache     * @param key     * @return     */    protected Object getFromCache(Cache cache, String key) {        final Cache.ValueWrapper valueWrapper = cache.get(key);        return null == valueWrapper ? null : valueWrapper.get();    }    /**     * 设置缓存数据     * @param cache     * @param key     * @param value     * @return     */    protected boolean putCache(Cache cache, String key, Object value) {        if (null == value) {            return false;        }        cache.put(key, value);        return true;    }    /**     * 删除缓存数据     * @param cache     * @param key     * @return     */    protected boolean evictFromCache(Cache cache,Object key){        if(null == key){            return false;        }        cache.evict(key);        return true;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

创建 Controller 类此处用 集成Mybatis时的controller

  • 加入缓存key private final static String TEST_REDIS = “test_redis”
  • 设置key-value : 
    Cache cache = cacheManager.getCache(TEST_REDIS); 
    putCache(cache,”test_aa”,”111111”);
/** * @author cwenao * @version $Id UserInfoController.java, v 0.1 2017-01-25 18:35 cwenao Exp $$ */@Controllerpublic class UserInfoController extends AbstractCacheSupport {    @Autowired    AccountInfoServer accountInfoServerImpl;    @Autowired    CacheManager cacheManager;    private final static String TEST_REDIS = "test_redis";    @RequestMapping("/accountInfo")    public String accountInfo(String name, ModelMap modelMap) {        Cache cache = cacheManager.getCache(TEST_REDIS);        putCache(cache,"test_aa","111111");        List<AccountInfo> accountInfoList = accountInfoServerImpl.selectByName(name);        modelMap.addAttribute("accountList", accountInfoList);        System.out.println(getFromCache(cache,"test_aa"));        return "userinfo/accountInfo";    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

测试

访问 http://localhost:10002/dbserver/accountInfo?name=cwenao

Key 存储在 test_redis~keys中

  • test_redis~keys中 test_redis为 Cache的key

key

value存储在 test_redis~keys中相对应的key

  • test_aa 为我们设置的redis key

value


代码

代码请移步 Github参考地址

如有疑问请加公众号(K171),如果觉得对您有帮助请 github start 

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

### 回答1: Springboot可以通过依赖管理器来实现对Redis集成。可以通过在项目的pom.xml文件中添加相应的依赖来实现Redis集成,然后在配置文件中配置Redis的相关参数,就可以实现SpringbootRedis集成了。 ### 回答2: Spring Boot中集成Redis可以通过以下步骤完成: 1. 引入Redis的依赖:在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在application.properties或application.yml文件中添加Redis的连接配置信息,包括host、port、password等,如: ```properties # Redis连接配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 3. 创建RedisTemplate实例:在需要使用Redis的类中注入RedisTemplate实例,该实例可以用于执行Redis的各种操作,如: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; ``` 4. 使用RedisTemplate进行操作:通过redisTemplate可以执行各种Redis操作,如存储、读取、删除等,例如: ```java // 存储数据 redisTemplate.opsForValue().set("key", "value"); // 读取数据 Object value = redisTemplate.opsForValue().get("key"); // 删除数据 redisTemplate.delete("key"); ``` 这样,就完成了Spring Boot集成Redis的过程。通过上述步骤,我们可以方便地在Spring Boot项目中使用Redis进行缓存、存储等操作,提高系统的性能和容错能力。 ### 回答3: Spring Boot可以通过添加对Redis的依赖来集成Redis。以下是一种常见的集成方式: 步骤1:在pom.xml文件中添加Redis的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 步骤2:在application.properties或application.yml文件中配置Redis连接信息,例如: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=your_password (如果Redis设置了密码的话) ``` 步骤3:创建一个Redis配置类,用于设置Redis连接工厂等配置信息。 ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; // 配置Redis连接工厂 @Bean public JedisConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port); return new JedisConnectionFactory(config); } // 配置Redis缓存管理器 @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder .fromConnectionFactory(redisConnectionFactory); return builder.build(); } } ``` 步骤4:在需要使用Redis的地方,使用`@Autowired`注解注入`RedisTemplate`对象,通过该对象进行Redis操作。 ```java @RestController public class RedisController { @Autowired private RedisTemplate<String, String> redisTemplate; @GetMapping("/get") public String getValue(String key) { return redisTemplate.opsForValue().get(key); } @PostMapping("/set") public void setValue(String key, String value) { redisTemplate.opsForValue().set(key, value); } } ``` 通过以上步骤,就可以在Spring Boot项目中集成Redis,并使用RedisTemplate对Redis进行读写操作了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值