<bean>
<property value="${redis.pool.minIdle}" />
<property value="${redis.pool.maxIdle}" />
<property value="${redis.pool.maxWaitMillis}" />
</bean>
<bean
>
<property value="true"></property>
<property value="${redis.ip}" />
<property value="${redis.port}" />
<property value="${redis.password}" />
<property value="${redis.timeout}" />
<property value="${redis.default.db}"></property>
<constructor-arg ref="jedisPoolConfig" />
</bean>
<bean>
<property ref="jedisConnectionFactory" />
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
<property>
<bean
></bean>
</property>
</bean>
</beans>
使用:
用注解注入Template,直接调用就好了。
@Repository
public class RedisService {
@Autowired
StringRedisTemplate stringRedisTemplate;
public void add(String key, User user, Long time) {
Gson gson = new Gson();
stringRedisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);
}
public void add(String key, List<User> users, Long time) {
Gson gson = new Gson();
String src = gson.toJson(users);
stringRedisTemplate.opsForValue().set(key, src, time, TimeUnit.MINUTES);
}
public User get(String key) {
String source = stringRedisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(source)) {
return new Gson().fromJson(source, User.class);
}
return null;
}
public List<User> getUserList(String key) {
String source = stringRedisTemplate.opsForValue().get(key);
if (!StringUtils.isEmpty(source)) {
return new Gson().fromJson(source, new TypeToken<List<User>>() {
}.getType());
}
return null;
}
public void delete(String key) {
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
}
���果是测试的话:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
@Autowired
RedisService redisService;
@Before
public void setUp() {
}
@Test
public void get() {
User user = new User();
user.setName("wangjianfeng");
user.setAge(22);
redisService.add("userByName:" + user.getName(), user, 10L);
List<User> list = new ArrayList<>();
list.add(user);
redisService.add("list", list, 10L);
User user1 = redisService.get("userByName:wangjianfeng");
Assert.notNull(user1, "user is null");
List<User> list2 = redisService.getUserList("list");
Assert.notNull(list2, "list is null");
}
}
SpringBoot使用Redis缓存:
Springboot提供了很多缓存管理器,比如:
SimpleCacheManager
EhCacheManager
CaffeineCacheManager
GuavaCacheManager
CompositeCacheManager
SpringData提供了缓存管理器:RedisCacheManager
在SpringBoot中,在程序入口,加上@EnableCaching注解自动化配置合适的管理器。
然后我们使用自己写代码配置的方式,修改RedisConfig添加@EnableCaching注解,并继承CachingCongigurerSupport
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
...
}
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx