Spring Boot+Redis+Annotation (七)

工程架构:


POM中添加缓存依赖包

 

<!-- spring-boot-starter-cache 依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
			<version>1.3.5.RELEASE</version>
		</dependency>

主要是Service接口

public City findCityName(String cityName);

	// 添加
	void add(City city);

	// 修改
	void update(String cityName, String description);

(2)实现的接口的类

@Service
public class CityServiceImpl implements CityService {

	// 模拟数据库存储
	private Map<String, City> maps = new HashMap<String, City>();

	/**
	 * 查找
	 */
	@Override
	@Cacheable(value="baseCityInfo")
	//调用这个方法,会从baseCityInfo的名称缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,
	//否则返回缓存中的对象
	public City findCityName(String cityName) {
		// 模拟数据库查询并返回
		return maps.get(cityName);
	}

	/**
	 * 添加
	 */
	@Override
	public void add(City city) {
		// TODO Auto-generated method stub
		maps.put(city.getCityName(), city);

	}

	/**
	 * 更新
	 */
	@Override
	@CachePut(value="baseCityInfo")
	//确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。
	public void update(String cityName, String description) {
		// 获得城市
		City city = maps.get(cityName);
		// 设置描述
		city.setDescription(description);

		// 保存到数据中
		maps.put(cityName, city);

	}

}



其他部分的配置文件,启动类忽略


测试类

@RunWith(SpringRunner.class)
// run
@SpringBootTest
// springboot test
public class TestApplication {
	// 日志对象
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CityServiceImpl.class);

	// 注入接口
	@Autowired
	public CityService cityService;

	/**
	 * 添加
	 */
	@Test
	public void testAdd() {
		// 城市对象
		City city = new City(8L, 10L, "上海", "人称魔都的地方");

		// 添加=> 向 redis 中存入数据
		cityService.add(city);

		// 从 redis 中取数据
		City citys = cityService.findCityName("上海");

		// 日志跟踪
		LOGGER.info(citys.toString());

	}

	/**
	 * 更新
	 */
	@Test
	public void testUpdate() {
		// 城市对象
		City city = new City(9L, 20L, "北京", "中国帝都");
		
		// 添加=> 向 redis 中存入数据
		cityService.add(city);

		// 从 redis 中取数据, 第一次查询
		City citys = cityService.findCityName("北京");
		// 日志跟踪
		LOGGER.info("first find BJ=>" + citys.toString());

		// 从 redis 中取数据, 第一次查询
		citys = cityService.findCityName("北京");
		// 日志跟踪
		LOGGER.info("second find BJ=>" + citys.toString());

		// 更新 city 的描述信息后查询
		cityService.update("北京", "很想去北京玩玩!");
		citys = cityService.findCityName("北京");
		// 日志跟踪
		LOGGER.info("update after BJ=>" + citys.toString());

	}
}

效果

1)执行添加方法


2)执行修改方法



https://github.com/yuanhangs/bearDay

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值