springboot09-redis

redis安装:

从redis官网下载redis包,解压后:

 

cmd执行命令启动本地redis:

D:

cd D:\Program Files\redis2.4.5\64bit

redis-server.exe redis.conf

起动成功后,使用Redis DeskTop Manager客户端连接访问

 

 

下面开始java代码:

 

1.导入依赖

<!--redis-->
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

2.配置RedisConfig

 1 package com.mlxs.springboot09.redis.config;
 2 
 3 
 4 import com.fasterxml.jackson.annotation.JsonAutoDetect;
 5 import com.fasterxml.jackson.annotation.PropertyAccessor;
 6 import com.fasterxml.jackson.databind.ObjectMapper;
 7 import org.springframework.cache.CacheManager;
 8 import org.springframework.cache.annotation.EnableCaching;
 9 import org.springframework.cache.interceptor.KeyGenerator;
10 import org.springframework.context.annotation.Bean;
11 import org.springframework.context.annotation.Configuration;
12 import org.springframework.data.redis.cache.RedisCacheManager;
13 import org.springframework.data.redis.connection.RedisConnectionFactory;
14 import org.springframework.data.redis.core.RedisTemplate;
15 import org.springframework.data.redis.core.StringRedisTemplate;
16 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
17 
18 import java.lang.reflect.Method;
19 
20 /**
21  * RedisConfig类描述:
22  *
23  * @author yangzhenlong
24  * @since 2017/3/16
25  */
26 @Configuration
27 @EnableCaching
28 public class RedisConfig {
29 
30     @Bean
31     public CacheManager cacheManager(RedisTemplate redisTemplate){
32         return new RedisCacheManager(redisTemplate);
33     }
34 
35     /**
36      * redisTemplate对象
37      * @param factory
38      * @return
39      */
40     @SuppressWarnings("SpringJavaAutowiringInspection")
41     @Bean
42     public RedisTemplate<String, String> redisTemplate( RedisConnectionFactory factory){
43         StringRedisTemplate redisTemplate = new StringRedisTemplate (factory);
44         redisTemplate.setValueSerializer(this.getRedisSerializer());
45         return redisTemplate;
46     }
47 
48     /**
49      * key生成策略
50      * @return
51      */
52     @Bean
53     public KeyGenerator keyGenerator(){
54         return new KeyGenerator() {
55             @Override
56             public Object generate(Object target, Method method, Object... params) {
57                 StringBuilder sb = new StringBuilder();
58                 sb.append(target.getClass().getName()).append(".")
59                         .append(method.getName()).append("-");//类名.方法名
60                 if(params.length > 0){
61                     for(Object param : params){
62                         sb.append("&" + param.toString());//&123&abc
63                     }
64                 }
65                 return sb.toString();
66             }
67         };
68     }
69 
70     /**
71      * json序列化对象
72      * @return
73      */
74     private Jackson2JsonRedisSerializer getRedisSerializer(){
75         Jackson2JsonRedisSerializer redisSerializer = new Jackson2JsonRedisSerializer(Object.class);
76         redisSerializer.setObjectMapper(this.getObjectMapper());
77         return redisSerializer;
78     }
79 
80     private ObjectMapper getObjectMapper(){
81         ObjectMapper objectMapper = new ObjectMapper();
82         objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
83         objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
84         return objectMapper;
85     }
86 }
View Code

3.单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApp.class)
public class RedisTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        List<User> userList = User.buildUser();
        for(User user : userList) {
            redisTemplate.opsForValue().set("user" + user.getId(), user);
        }

        Object user1 = redisTemplate.opsForValue().get("user1");
        System.out.println("user1:" + user1);
    }
}
View Code

查看redis中的值:

控制台打印:

 

4.写service,使用key生成策略

@Service
public class UserService {

    @Cacheable(value = "userCache", keyGenerator = "keyGenerator")//设置redis 和
    public List<User> users(){
        return User.buildUser();
    }
}
View Code

5.写controller,调用service。第一次调用,会在redis写入值,第二次调用不会再进service,直接从redis读取值

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/users")
    public List<User> list(){
        return userService.users();
    }
}

启动springboot启动类,访问http://localhost:8080/users

查看reids

 

posted @ 2017-03-16 15:35  艺言弈行  阅读(331)  评论(0编辑  收藏  举报