BEIJING — China signed a huge, long-awaited deal on Wednesday to buy Russian natural gas, giving China a new source of clean energy and Russia a diplomatic boost as it faces international sanctions for its aggressive actions in Ukraine.

With the stroke of a pen, Russia significantly shifted its economic relations with its neighbors, creating a new major export market to the east and reducing its reliance on European customers at a time when its relations with the West are at their lowest point since the Cold War.

Russian President Vladimir Putin called the deal a “watershed event” and said implementation would start at once.

The 30-year deal was announced after meetings in Shanghai between Putin and Chinese President Xi Jinping. It is worth an estimated $400 billion, Alexei Miller, chief executive of the Russian energy giant Gazprom, told Russian media.

The deal marked a new partnership between two countries that have at times mistrusted each other but have also sought to counter U.S. influence in global affairs.

China’s booming economy has created a growing need for energy, especially cleaner sources of power, given its reliance on coal, which has created major pollution problems.

The agreement allows Russia to diversify its gas exports at a time when the Ukrainian crisis has accelerated calls in Europe to rely less on energy supplies from Russia. Currently, Europe gets roughly 30 percent of its gas from Russia.

U.S. Treasury Secretary Jack Lew appealed to China in a visit last week to avoid actions that might limit the impact of recent Western sanctions against Russia. But a U.S. official, who was not authorized to speak by name, said the United States would distinguish between deals that have long been in the works – such as this one – and new agreements that seek to fill space left by U.S. and EU sanctions.

The deal will involve developing natural gas fields in Russia and building pipelines from Russia to China. The construction of the infrastructure alone is expected to top $70 billion, said Mikhail Krutikhin, an energy and oil analyst at Rusenergy, a Moscow think tank.